Read file with multiple spaces word by word c++ - c++

I want to read .txt file word by word and save words to strings. The problem is that the .txt file contains multiple spaces between each word, so I need to ignore spaces.
Here is the example of my .txt file:
John Snow 15
Marco Polo 44
Arya Stark 19
As you see, each line is another person, so I need to check each line individualy.
I guess the code must look something like this:
ifstream file("input.txt");
string line;
while(getline(file, line))
{
stringstream linestream(line);
string name;
string surname;
string years;
getline(linestream, name, '/* until first not-space character */');
getline(linestream, surname, '/* until first not-space character */');
getline(linestream, years, '/* until first not-space character */');
cout<<name<<" "<<surname<<" "<<years<<endl;
}
Expected result must be:
John Snow 15
Marco Polo 44
Arya Stark 19

You can just use operator>> of istream, it takes care of multiple whitespace for you:
ifstream file("input.txt");
string line;
while(!file.eof())
{
string name;
string surname;
string years;
file >> name >> surname >> years;
cout<<name<<" "<<surname<<" "<<years<<endl;
}

Related

Read elements from a txt file that are separeted by a character

I'am working on a program where there are first names, last names and a numbers on a file and i need to read that information into my program. My actual problem is that there is people who doesnt have a second name or second last name. To solve the issue I started trying to read from a file until a specific character is found, For example:
Robert, Ford Black,208 //Where Robert is the first name, and Ford Black are his two last names
George Richard, Bradford,508 //Where George Richard are both his first names, and Bradford is his only last
name
I am saving this information in three separeted string, one that will store first and second name, first last and second last name and the third one for the numbers.
I'm trying to only use native libraries from c++.
I've been reading that getline(a,b,c) and IStringStream can actually solve my problem but I don't know how to correctly implement it
It's just a matter of using std::getline with a delimiter character to read out of the string stream. See a simplified example (no error checking) below:
for (std::string line; std::getline(std::cin, line); )
{
std::string firstName, lastName;
std::istringstream iss(line);
std::getline(iss, firstName, ','); // A comma delimits end-of-input
iss >> std::ws; // Skip over any whitespace characters
std::getline(iss, lastName); // Read remaining line
std::cout << "First Name: " << firstName << std::endl;
std::cout << "Last Name: " << lastName << std::endl;
}
Note the line iss >> std::ws; using std::ws from <iomanip> is there to eat up extra whitespace characters (which appear after your comma, in your example).
I'm assuming the C++ line comments in the input are only an annotation for this question, and not part of the actual input.
#include<bits/stdc++.h>
using namespace std;
int main()
{
ifstream myfile("files.txt");
string fullname;
while(getline(myfile,fullname,'/')) break; //here im reading till the first / is acquired and the entire string is stored in "fullname"
string firstname,lastname;
size_t pos=fullname.find(',');
firstname=fullname.substr(0,pos); //store the firstname
lastname=fullname.substr(pos+1);// storee the lastname
cout<<firstname<<" "<<lastname;
}
As the question posed was to read names im assuming before the digit if there were a " / " you can read upto the first occurance of /. this will give you the fullname. Then using the substr on the fullname and find the occurance of a comma if at all it exists. All the characters to the left of position of comma will form your first name and the rest on the right of the position of comma will form the lastname.

Parse String into Several Parts Using a stringstream

I have an input file that has multiple lines in the current format:
[message1]/[message2]/[message3]
I have to extract [message#] and put each into a separate container (vector, array, etc). Is there an easy way to do this with a stringstream?
Note: [message#] will NOT contain the character '/'.
I have initially tried to do this:
istringstream iss;
iss >> message1 >> "/" >> message2 >> "/" >> message3;
but it wouldn't work. Any hints appreciated.

Reading in a file by int, then words

I have a text file that resembles
1 \t words words words words
2 \t words words words words
where the # is the line #, followed by a tab, then followed by random words
I need to read in the int, store it, then skip the \t, and read in each word individually while keeping track of that words position.
I was hoping I could it with getline(file, word, ' '), and a counter but that grabs my first word as 1 \t words.
Any help or suggestions would be much appreciated.
use stringstream and getline,
getline(file, line);
std::stringstream ssline(line);
int num;
ssline >> num;
std::string word;
while(ssline >> word){
// do whatever you want.
}
Assuming that you can't say how many words there are on a line, then the simple answer is to do it in two steps.
Read a whole line into a string with getline
Place that string into a std::istringstream and read the line number and following words from the std::istringstream
then repeat from step 1

Getline and ifstream?

I'm having an issue with ifstream and getline in conjucntion.
I have a text document:
1020123456
Madison Williams
90
88
79
86
90
And want to assign the name into a students[0].name where students is a struct of type student.
I tried using
inFile >> students[0].id;
getline(inFile, students[0].name);
"cout << students[0].id" yields the ID properly but .name does nothing.
What am I doing wrong here?
And "inFile.getline(students[0].name)" yields errors.
There's a '\n' character there after your numbers. When you inFile >> students[0].id; you read the number, but stop at the '\n' character. Then, when you getline(), there's that '\n' character left in your stream, so it reads an empty string, skips the '\n', and then moves on to the next line (which is where your name is).
You need to skip the '\n' after you read a number and before you call getline(). Calling
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); will ignore what's left in inFile until it meets the '\n' character. So change it to:
inFile >> students[0].id;
inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(inFile, students[0].name);
// continue as normal...

C++ cin whitespace question

Programming novice here. I'm trying to allow a user to enter their name, firstName middleName lastName on one line in the console (ex. "John Jane Doe"). I want to make the middleName optional. So if the user enters "John Doe" it only saves the first and last name strings. If the user enters "John Jane Doe" it will save all three.
I was going to use this:
cin >> firstName >> middleName >> lastName;
then I realized that if the user chooses to omit their middle name and enters "John Doe" the console will just wait for the user to enter a third string... I know I could accomplish this with one large string and breaking it up into two or three, but isn't there a simpler way to do it with three strings like above?
I feel like I'm missing something simple here...
Thanks in advance.
Use getline and then parse using a stringstream.
#include <sstream>
string line;
getline( cin, line );
istringstream parse( line );
string first, middle, last;
parse >> first >> middle >> last;
if ( last.empty() ) swap( middle, last );