gpt4 book ai didi

c++ - 将字符串转换为 int 数组

转载 作者:行者123 更新时间:2023-11-28 02:25:11 26 4
gpt4 key购买 nike

我有以下问题。我想将 "10 15 30" 之类的字符串转换为具有 10, 15, 30 整数的 int 数组。我在谷歌上搜索了很多,但通常解决方案包括 vector (我不熟悉)或其他更复杂的解决方案。我找到了这样的代码:

#include <cstdio>
void foo ( char *line ) {
int num, i = 0, len;
while ( sscanf( line, "%d%n", &num, &len) == 1 ) {
printf( "Number %d is %d; ", i, num );
line += len;
i++;
}
}
int main ( ) {
char test[] = "12 45 6 23 100";
foo( test );
return 0;
}

它以我想要的方式工作并从字符串中提取数字,但我不明白部分:

line += len;

谁能解释一下它是如何工作的?为什么要向字符串添加 len(即 int)?

最佳答案

C++ 的解决方案:

#include <iostream>
#include <sstream>
#include <vector>

std::vector< int > foo ( char *c_str ) {
std::istringstream line( c_str );
std::vector< int > numbers;
for ( int n; line >> n; )
numbers.push_back( n );
return numbers;
}

int main ( ) {
char test[] = "12 45 6 23 100";
std::vector< int > numbers = foo( test );
for ( int n : numbers )
std::cout << n << ' ';
return 0;
}

输出:

12 45 6 23 100

关于c++ - 将字符串转换为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com