Storing Two Spaced String in vector<string> - c++

Recently I faced a problem
But before that I will tell you what is the reference
Consider this program
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> RS;
string word;
while(cin>>word)
RS.push_back(word);
}
This code stores each word of spaced string in vector
But the problem comes here .....
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> RS,FS;
string word;
while(cin>>word)
RS.push_back(word);
while(cin>>word)
FS.push_back(word);
}
Here the motive is to store the string words of first line in RS
and of second line in FS vectors
But it doesn't stop at the end of one line and store all words in RS
and FS remains empty.
Please Suggest a way to do the same program correctly
or
If you know more efficient way you are more than Welcome
Thanks in Advance

Use getline and istringstream, separately for each sentence, and then push_back each word in them:
string line;
getline(cin, line); //Get sentence 1
istringstream iss1(line);
while ( iss1 >> word) {
RS.push_back(word);
}
getline(cin, line); //Get sentence 2
istringstream iss2(line);
while ( iss2 >> word) {
FS.push_back(word);
}
The newline character ('\n') acts as the delimiting character for getline().

Related

How to read input from file and pair into a map in C++

I am trying to read through a text file that can possibly look like below.
HI bye
goodbye
foo bar
boy girl
one two three
I am trying to take the lines with only two words and store them in a map, the first word would be the key and second word would be the value.
below is the code I came up with but I can't figure out how to ignore the lines that do not have two words on them.
this only works properly if every line has two words. I understand why this is only working if every line has two words but, I'm not sure what condition I can add to prevent this.
pair myPair;
map myMap;
while(getline(file2, line, '\0'))
{
stringstream ss(line);
string word;
while(!ss.eof())
{
ss >> word;
myPair.first = word;
ss >> word;
myPair.second = word;
myMap.insert(myPair);
}
}
map<string, string>::iterator it=myMap.begin();
for(it=myMap.begin(); it != myMap.end(); it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
Read two words into a temporary pair. If you can't, do not add the pair to the map. If you can read two words, see if you can read a third word. If you can, you have too many words on the line. Do not add.
Example:
while(getline(file2, line, '\0'))
{
stringstream ss(line);
pair<string,string> myPair;
string junk;
if (ss >> myPair.first >> myPair.second && !(ss >> junk))
{ // successfully read into pair, but not into a third junk variable
myMap.insert(myPair);
}
}
let me suggest a little different implementation
std::string line;
while (std::getline(infile, line)) {
// Vector of string to save tokens
vector <string> tokens;
// stringstream class check1
stringstream check1(line);
string intermediate;
// Tokenizing w.r.t. space ' '
while(getline(check1, intermediate, ' ')) {
tokens.push_back(intermediate);
}
if (tokens.size() == 2) {
// your condition of 2 words in a line apply
// process 1. and 2. item of vector here
}
}
You can use fscanf for take input from file and sscanf for take input from string with format. sscanf return how many input successfully take with given format. so you can easily check, how many word have a line.
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
int main()
{
char line[100];
FILE *fp = fopen("inp.txt", "r");
while(fscanf(fp, " %[^\n]s", line) == 1)
{
cout<<line<<endl;
char s1[100], s2[100];
int take = sscanf(line, "%s %s", s1, s2);
cout<<take<<endl;
}
return 0;
}

Splitting a string up into individual words and placing them in a vector

I want to be able to place each individual word of the string of any size into a vector. This is what I have so far:
vector <string> broken;
while(choice != " "){
int space = choice.find(" ")-1;
string word = choice.substr(0,space);
broken.push_back(word);
choice = choice.substr(space+1);``
cout << choice;
}
Any help would be greatly appreciated!
The easiest way is to use stringstream, you can insert the multiword string in the stringstream then make a while loop inserting from the stringstream to another string, then you'll have each word separated in each iteration of the loop.
stringstream ss;
ss << choice;
vector <string> broken;
string word;
while(ss >> word){
broken.push_back(word);
}
One possibility is using an istringstream :
istringstream iss(choice);
vector<string> broken{istream_iterator<string>{iss},
istream_iterator<string>{}};
You'll need to #include <sstream> and #include <iterator>.

c++ found an example on splitting strings trying to figure out why change to it changes result

I'm learning about splitting strings for a program in class, and i came across this example.
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string str = "23454323 ABCD EFGH";
std::istringstream iss(str);
std::string word;
while(iss >> word)
{
std::cout << word << '\n';
}
}
I modified so that the user instead inputs the string,but if I input the string stored in str i get 23454323 and not the other material in the string.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
string str;
cout<<"Enter a postfix with a space between each object:";
cin>>str;
istringstream iss(str);
string word;
while(iss >> word)
{
cout << word << '\n';
}
}
Ok, thanks for the help everyone got it!
You need to modify your input code a little for this to work. Use:
getline(cin, str);
instead of:
cin >> str;
The latter will stop reading a string on whitespace characters.
Because you use the same input operator as for istringstream when you input from cin and it always breaks on whitespace.
That means you only read a single word from the user. You want to use std::getline.
Just as iss >> word reads a single space-separated word from iss, so cin >> str just reads the first word from cin.
To read a whole line, use getline(cin, str).
(Also, get out of the habit of dumping namespace std into the global namespace. It will cause problems as your programs grow.)

is it possible to read from a specific character in a line from a file in c++?

Hey all so I have to get values from a text file, but the values don't stand alone they are all written as this:
Population size: 30
Is there any way in c++ that I can read from after the ':'?
I've tried using the >> operator like:
string pop;
inFile >> pop;
but off course the whitespace terminates the statement before it gets to the number and for some reason using
inFile.getline(pop, 20);
gives me loads of errors because it does not want to write directly to string for some reason..
I don't really want to use a char array because then it won't be as easy to test for the number and extract that alone from the string.
So is there anyway I can use the getline function with a string?
And is it possible to read from after the ':' character?
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
string fname;
cin >> fname;
ifstream inFile;
inFile.open(fname.c_str());
string pop1;
getline(inFile,pop1);
cout << pop1;
return 0;
}
ok so here is my code with the new getline, but it still outputs nothing. it does correctly open the text file and it works with a char array
You are probably best to read the whole line then manipulate the string :-
std::string line;
std::getline(inFile, line);
line = line.substr(19); // Get character 20 onwards...
You are probably better too looking for the colon :-
size_t pos = line.find(":");
if (pos != string::npos)
{
line = line.substr(pos + 1);
}
Or something similar
Once you've done that you might want to feed it back into a stringstream so you can read ints and stuff?
int population;
std::istringstream ss(line);
ss >> population;
Obviously this all depends on what you want to do with the data
Assuming your data is in the form
<Key>:<Value>
One per line. Then I would do this:
std::string line;
while(std::getline(inFile, line))
{
std::stringstream linestream(line);
std::string key;
int value;
if (std::getline(linestream, key, ':') >> value)
{
// Got a key/value pair
}
}

C++ file input problem

Hi Guys! I have the following code:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define MAXN 301
string names[MAXN];
vector<string> names_vec;
int main(int argc, char **argv)
{
ifstream fin(argv[1]);
int n;
fin>>n;
string line;
while(getline(fin, line))
names_vec.push_back(line);
for(int i=0; i<names_vec.size(); i++)
cout<<names_vec[i]<<endl;
return 0;
}
and names.in file for input:
5
CLEOpatra
AISHWARYA rai
jOHn f. KeNNeDy
leonardo DA Vinci
tyleR durdeN
When i compile it and run it first prints empty line, that names_vec[0] is empty line. Can anyone explain why and how can I fix it?
The problem is that you're mixing the >> operator with calls to getline. Generally, you want to use one or the other, but not both of them together.
The reason you get an empty string in your vector is because >> will NOT consume the whitespace which causes it to stop. That is, it reads the "5", finds the newline character after it, and then stops, leaving the newline character in the ifstream.
Then, the call to getline encounters the newline character and immediately says, "Done! I read a line!". It consumes the newline character and returns the entire string leading up to it -- which in this case was the empty string.
If you know that your data will be formatted properly (no invalid input), it might be easiest just to use >> to read the entire file. Otherwise, I would recommend using getline to read each line one at a time, then using a stringstream object to parse the data out of the line.
EDIT
I just noticed that the rest of your input has first/last names separated by spaces. Since >> stops on spaces, it would probably be easiest to use getline to read the entire file. Example of reading the 5:
string line;
getline(fin, line);
stringstream converter;
converter << line;
int n;
converter >> n;