I need to read something like:
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.
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.
The built-in function in c programming is getline() which is used for reading the lines from the stdin. But we can also use other functions like getchar() and scanf() for reading the lines.
"Standard input" refers to a specific input stream, which is tied to file descriptor 0. It's the stream from which scanf , getchar , gets (which you should never use), etc., all read. Basically, any stdio input function that doesn't take a FILE * as an argument is reading from standard input.
If you have an unknown number of entries spread across an unknown number of lines, ending at EOF:
int n;
while(cin >> n)
vector_of_int.push_back(n);
If you have a known number of entries spread across an unknown number of lines:
int n;
int number_of_entries = 20; // 20 for example, I don't know how many you have.
for(int i ; i < number_of_entries; ++i)
if(cin >> n)
vector_of_int.push_back(n);
If you have an uknown number of entries on a single line:
std::string str;
std::getline(std::cin, str);
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
If you have a unknown number of entries spread across a known number of lines:
for(int i = 0; i < number_of_lines; ++i) {
std::string str;
if(std::getline(std::cin, str)) {
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
}
}
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With