Stringstream gets the input of string (line).
Then it cuts based on space.
I used it when getting rows of integer in one line, cut by one number(formatted in string) using stringstream, and changed into int using atoi( [name_of_string].c_str()) using a while loop.
I used atoi( [].c_str) because the version of c++ was below 11.
This is the sample code:
#include <iostream>
#include <string>
#include <sstream> //for stringstream
#include <stdlib.h> //for atoi
using namespace std;
int main()
{
cout << "Enter row or integers separated by spaces: ";
string convert_to_int;
getline(cin, convert_to_int);
stringstream ss(convert_to_int);
int intarr[100];
string str;
int count = 0;
int past;
string result;
while(ss >> str) {
int current = atoi( str.c_str() );
intarr[count] = current;
if (count != 0) {
past = intarr[count - 1];
//result = (past == current) ? "same\n" : "different\n";
cout << "The number " << past << " and " << current << " are " << ((past == current) ? "same\n" : "different\n");
}
count ++;
}
return 0;
}
reference: https://www.acmicpc.net/board/view/25973
https://stackoverflow.com/questions/7663709/how-can-i-convert-a-stdstring-to-int
cin, getline skipping input (0) | 2020.09.03 |
---|---|
비주얼 스튜디오에서 MinGW를 이용해 c++파일 컴파일하기 (Run c++ file in Visual Studio Code using MinGW) (0) | 2020.08.28 |
Int to string, string to char* in c++ (0) | 2020.07.19 |
Ternary if statement (0) | 2020.07.19 |
Double to int cast (0) | 2020.07.18 |
댓글 영역