如何从C ++中的标准输入读取n个整数?
我需要阅读以下内容:
5 60 35 42
2 38 6
5 8
300 1500 900
然后保存数组中的第一行。
And then save the first line in an array. After calling other functions do the same with the next line, and so on.
我尝试使用 gets()
然后使用 sscanf()
从字符串中扫描整数,但我不知道如何从字符串中读取n个数字。
I try with gets()
and then use sscanf()
to scan the integers from the string, but I don't know how to read n numbers from a string.
我以前看过这样的输入文件。如果速度比错误检测更重要,您可以使用自定义例程。这是一个类似于我使用:
I've seen input files like this for competitions before. If speed is more of an issue than error detection, you could use a custom routine. Here's one similar to that I use:
void readintline(unsigned int* array, int* size) {
char buffer[101];
size=0;
char* in=buffer;
unsigned int* out=array;
fgets(buffer, 100, stdin);
do {
*out=0;
while(*in>='0') {
*out= *out* 10 + *in-'0';
++in;
}
if (*in)
++in; //skip whitespace
++out;
} while(*in);
size = out-array;
}
如果一行中有超过100个字符,
It will destroy your memory if there's more than 100 characters on a line, or more numbers than array can hold, but you won't get a faster routine to read in lines of unsigned ints.
另一方面,如果你想要简单:
On the other hand, if you want simple:
int main() {
std::string tmp;
while(std::getline(std::cin, tmp)) {
std::vector<int> nums;
std::stringstream ss(tmp);
int ti;
while(ss >> ti)
nums.push_back(ti);
//do stuff with nums
}
return 0;
}