question about getline()

I have a string which include numbers only, but the type is string. example: string1="12 52 36 14 26 36" and I want to get all the numbers into another array which type is int, such as array[0]=12, array[2]=36. I used the while(getline()) loop and it cannot be stopped. how to fix this problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  // Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
        string input;
    while(getline(cin,input,' ')){
        int temp=stoi(input,nullptr,10);
        cout<<temp<<endl;
    }
    return 0;
}
looping on unformatted input is generally works until stream is exhausted. But cin is "infinite" stream: it just asks user for more in no characters are avaliable.

You can:
a) Send end of stream manually by pressing Ctrl+Z on a newline (assuming you are using Windows)

b) read single line and then parse it:
1
2
3
4
std::string str;
std::getline(cin, str);
std::istringstream input(str);
//Your original loop 
thank you so much! I have fixed that problem ,thank you for your code
Topic archived. No new replies allowed.