How would I get a list of numbers from the user and then tokenize them.
This is what I have but it doesn't get anything except for the first number:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line = "";
cin >> line;
stringstream lineStream(line);
int i;
vector<int> values;
while (lineStream >> i)
values.push_back(i);
for(int i=0; i<values.size(); i++)
cout << values[i] << endl;
system("PAUSE");
return 0;
}
Related Posts:
C++, Going from string to stringstream to vector
Int Tokenizer
Here is probably the easiest way to read values from cin into a container:
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> values;
std::copy(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(values));
// For symmetry with the question copy back to std::cout
std::copy(
values.begin(),
values.end(),
std::ostream_iterator<int>(std::cout,"\n"));
}
I believe cin >> breaks on whitespace, which means you're only getting the first number entered.
try:
getline(cin, line);
Like Donnie mentioned cin breaks on whitespace, so do overcome this we can use a 'getline()', the following example works nicely:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line = "";
::getline(std::cin,line,'\n');
std::stringstream lineStream(line);
int i;
std::vector<int> values;
while (lineStream >> i)
values.push_back(i);
for(int i=0; i<values.size(); i++)
cout << values[i] << endl;
system("PAUSE");
return 0;
}
on top of main
string line = "";
getline (cin, line );
stringstream lineStream(line);
Yep, and is the string version of getline, no the istream one.
OK: Pavel Minaev has the best answer.
But all the people mentioning that cin breaks on white space.
That is a good thing (because it also ignores white space);
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int i;
vector<int> values;
// prefer to use std::copy() but this works.
while (std::cin >> i)
{
values.push_back(i);
}
// prefer to use std::copy but this works.
for(vector<int>::const_iterator loop = values.begin();loop != values.end();++loop)
{
cout << *loop << endl;
}
return 0;
}
Related
How do I accept an unknown number of lines in c++? Each line has two strings in it separated by a space. I tried the solutions mentioned in This cplusplus forum, but none of the solutions worked for me. One of the solutions works only when Enter is pressed at the end of each line. I am not sure if the \n char will be given at the end of my input lines. What are my options?
My current attempt requires me to press Ctrl+Z to end the lines.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line;
while(cin>>line and cin.eof()==false){
cout<<line<<'\n';
}
return 0;
}
I would like to take an unknown number of strings as shown below:
cool toolbox
aaa bb
aabaa babbaab
Please don't flag this as a duplicate, I really tried all I could find! I tried the following solution on the above given link by m4ster r0shi (2201), but it did not work for me.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
string word;
string line;
// get the whole line ...
getline(cin, line);
// ... then use it to create
// a istringstream object ...
istringstream buffer(line);
// ... and then use that istringstream
// object the way you would use cin
while (buffer >> word) words.push_back(word);
cout << "\nyour words are:\n\n";
for (unsigned i = 0; i < words.size(); ++i)
cout << words[i] << endl;
}
And this other solution also did not work: other soln, and I tried this SO post too: Answers to similar ques. This one worked for my example, but when I pass only one line of input, it freezes.
// doesn't work for single line input
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line ="-1";
vector<string>data;
while(1){
cin>>line;
if(line.compare("-1")==0) break;
data.push_back(line);
line = "-1";
}
for(int i =0;i<data.size();i+=2){
cout<<data[i]<<' '<<data[i+1]<<'\n';
}
return 0;
}
If each line has two words separated by whitespace, then perhaps you should have a Line struct which contains two std::strings and overloads the >> operator for std::istream.
Then you can just copy from std::cin into the vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
struct Line {
std::string first;
std::string second;
};
std::istream& operator>>(std::istream& i, Line& line) {
return i >> line.first >> line.second;
}
int main() {
std::vector<Line> lines;
std::copy(
std::istream_iterator<Line>(std::cin),
std::istream_iterator<Line>(),
std::back_inserter(lines)
);
for (auto &[f, s] : lines) {
std::cout << f << ", " << s << std::endl;
}
return 0;
}
A test run:
% ./a.out
jkdgh kfk
dfgk 56
jkdgh, kfk
dfgk, 56
I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i=0;
char a[100][100];
do {
cin>>a[i];
i++;
}while( strcmp(a[i],"\n") !=0 );
for(int j=0;j<i;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
Here , i want to exit the do while loop as the users hits enter .But, the code doesn't come out of the loop..
The following reads one line and splits it on white-space. This code is not something one would normally expect a beginner to write from scratch. However, searching on Duckduckgo or Stackoverflow will reveal lots of variations on this theme. When progamming, know that you are probably not the first to need the functionality you seek. The engineering way is to find the best and learn from it. Study the code below. From one tiny example, you will learn about getline, string-streams, iterators, copy, back_inserter, and more. What a bargain!
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main() {
using namespace std;
vector<string> tokens;
{
string line;
getline(cin, line);
istringstream stream(line);
copy(istream_iterator<string>(stream),
istream_iterator<string>(),
back_inserter(tokens));
}
for (auto s : tokens) {
cout << s << '\n';
}
return 0;
}
First of all, we need to read the line until the '\n' character, which we can do with getline(). The extraction operator >> won't work here, since it will also stop reading input upon reaching a space. Once we get the whole line, we can put it into a stringstream and use cin >> str or getline(cin, str, ' ') to read the individual strings.
Another approach might be to take advantage of the fact that the extraction operator will leave the delimiter in the stream. We can then check if it's a '\n' with cin.peek().
Here's the code for the first approach:
#include <iostream> //include the standard library files individually
#include <vector> //#include <bits/stdc++.h> is terrible practice.
#include <sstream>
int main()
{
std::vector<std::string> words; //vector to store the strings
std::string line;
std::getline(std::cin, line); //get the whole line
std::stringstream ss(line); //create stringstream containing the line
std::string str;
while(std::getline(ss, str, ' ')) //loops until the input fails (when ss is empty)
{
words.push_back(str);
}
for(std::string &s : words)
{
std::cout << s << '\n';
}
}
And for the second approach:
#include <iostream> //include the standard library files individually
#include <vector> //#include <bits/stdc++.h> is terrible practice.
int main()
{
std::vector<std::string> words; //vector to store the strings
while(std::cin.peek() != '\n') //loop until next character to be read is '\n'
{
std::string str; //read a word
std::cin >> str;
words.push_back(str);
}
for(std::string &s : words)
{
std::cout << s << '\n';
}
}
You canuse getline to read ENTER, run on windows:
//#include<bits/stdc++.h>
#include <iostream>
#include <string> // for getline()
using namespace std;
int main()
{
int i = 0;
char a[100][100];
string temp;
do {
getline(std::cin, temp);
if (temp.empty())
break;
strcpy_s(a[i], temp.substr(0, 100).c_str());
} while (++i < 100);
for (int j = 0; j<i; j++)
{
cout << a[j] << endl;
}
return 0;
}
While each getline will got a whole line, like "hello world" will be read once, you can split it, just see this post.
I am attempting to write a program which can read in a text file, and store each word in it as an entry in a string type vector. I am sure that I am doing this very wrong, but it has been so long since I have tried to do this that I have forgotten how it is done. Any help is greatly appreciated. Thanks in advance.
Code:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile;
vector<string>::iterator it;
it = input.begin();
readFile.open("input.txt");
for (it; ; it++)
{
char cWord[20];
string word;
word = readFile.get(*cWord, 20, '\n');
if (!readFile.eof())
{
input.push_back(word);
}
else
break;
}
cout << "Vector Size is now %d" << input.size();
return 0;
}
One of the many possible ways is a simple:
std::vector<std::string> words;
std::ifstream file("input.txt");
std::string word;
while (file >> word) {
words.push_back(word);
}
operator >> takes care of only words divided by whitespaces (including new-lines) being read.
And in case you would be reading it by lines, you might also need to explicitly handle empty lines:
std::vector<std::string> lines;
std::ifstream file("input.txt");
std::string line;
while ( std::getline(file, line) ) {
if ( !line.empty() )
lines.push_back(line);
}
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> input;
ifstream readFile("input.txt");
copy(istream_iterator<string>(readFile), {}, back_inserter(input));
cout << "Vector Size is now " << input.size();
}
Or, shorter:
int main()
{
ifstream readFile("input.txt");
cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size();
}
I'm not going to explain, because there's about a zillion explanations on StackOverflow already :)
I am trying something like this:
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main()
{
string inputStr;
vector <string> strVector;
cin.getline(inputStr,200);
int i=0;
while (inputStr!=NULL){ //unless all data is read.
strVector[i]=getline(inputStr," ");
i++;
}//while.
for (int j=0; j<strVector.size(); j++){
cout<< strVector[j];
cout<<endl;
}
} //main.
Any one who can help. I am trying to store my input string in vector string and then I can push_back my ith string.
Much of your code involving inputString is invalid. There is no getline member of istream that takes a std::string, so this is invalid:
cin.getline(inputStr,200);
What you want there instead is the global getline:
getline(cin, inputStr);
Second, there is no global getline which reads directly from a std::string, so this is invalid:
strVector[i]=getline(inputStr," ");
What you want to use there is an istringstream. Altogether, your code might look something like this:
std::getline(std::cin, inputStr);
std::istringstream iss(inputStr);
std::string word;
// read from the istringstream until failure
while (std::getline(iss,word,' '))
strVector.push_back(word);
If you want to delimit on whitespace(including tabs) then you can use operator>> instead of getline.
I think you are looking for the push_back method of the std::vector template
Here is nother way:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> strVec;
string str;
cout<<"Enter # to quit \n\n";
int i=0;
while (str!="#")
{
cout<<"Input text No. "<<i+1 <<" here > ";
cin>>str ;
strVec.push_back(str);
i++;
}
cout<<"\nStored text\n----------\n";
for (int j=0; j<strVec.size()-1; j++) cout<<j+1<<" "<< strVec[j]<<"\n";
cout<<"\n\n";
return(0);
}