C++ Easy way to ignore first word of input - c++

I am writing a program to read a text file line by line, store the line values in a vector, do some processing then write back to a new text file. This is what the text file typically looks like:
As you can see, there are two columns: one for the frame number and another for the time. What I want is only the second column (aka the time). There can be hundreds, if not thousands of lines in the text file. Previously I have been manually deleting the frame number column which i'd rather not do. So my question is: is there an easy way to edit my current code so that when I read the file with getline() it skips the first word and only gets the second? Here is the code that I use to read the text file. Thanks
ifstream sysfile(sys_time_dir);
//Store lines in a vector
vector<string> sys_times;
string textline;
while (getline(sysfile, textline))
{
sys_times.push_back(textline);
}

Since you have two numbers in each line, you can read two numbers and ignore the first number.
vector<double> sys_times;
int first;
double second;
while ( sysfile >> first >> second )
{
sys_times.push_back(second);
}

std::string ignore_me;
while (sysfile >> ignore_me, getline(sysfile, textline)) {
...
This utilizes the comma operator, reading in the first word (here defining "word" as a continuous sequence of non-space characters) of the line, but ignoring the result, then using getline to read the rest of the line.
Note that for the specific data format you describe, I would rather choose what RSahu showed in their answer. My answer is more general to the problem of "skipping the first word and reading the rest of the line".

Related

Ignoring remaining newlines and white space when reading input file (C++)

I have a function that reads a text file as input and stores the data in a vector.
It works, as long as the text file doesn't contain any extra new lines or white space.
Here is the code I currently have:
std::ifstream dataStream;
dataStream.open(inputFileName, std::ios_base::in);
std::string pushThis;
while(dataStream >> pushThis){
dataVector.push_back(pushThis);
}
For example:
safe mace
bait mate
The above works as an input text file.
This does not work:
safe mace
bait mate
Is there any way to stop the stream once you reach the final character in the file, while still maintaining separation via white space between words in order to add them to something like a vector, stack, whatever?
i.e. a vector would contain ['safe', 'mace', 'bait', 'mate']
Answer:
The problem came from having two streams, one using !dataStream.eof() and the other using dataStream >> pushThis.
Fixed so that both use dataStream >> pushThis.
For future reference for myself and others who may find this:
Don't use eof() unless you want to grab the ending bit(s) of a file (whitespace inclusive).

C++ getline in for loop

I learn to program in c++ with previous experience with python and R. Id say I understand for loops well, but now I found out that I do not know nothig about them. Here is piece of code.
for (int i = 0; i != 1; ){
string name;
getline(infile, name);
if (name == end_input){
i = 1;
}
else{
names.push_back(name);
}
}
Whole program should (and do) read names (name) from file infile and store them into names string. Than I want them to store in another file. When I look on the code, I would thing c++ do following instructions:
create integer i and set it to 0
create string name
read the line from infile and store this line into names string vector.
this will repeat unless name == end_input
From this I would say that c++ will store first line in input file again and again because I didnt tell him to jump to next line after getline the first line. But program reads all names from that file, line by line as expected by author. How is that possible?
Thank you.
getline automatically moves to the next line after reading a line.
Also a do while loop might serve your purposes better here.
When an inbuilt function does not behave as you expected, the logical next step should be to check the Documentation. If you do, you will see the following:
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
Which answers your Question.

How do I loop through input line by line and also go through each of those lines in C++;

So I'm trying to go through input line by line. Each line in the input is formatted like this:
Words_More words_even more words_What I Need to Go Through_ Random_ Random_Etc.
With a random amount of word clusters (The words separated by '_')
I want, for each line, to be able to ignore all the words until I get to the fourth word cluster which in the example I gave would be: "What I Need To Go Through" and then store those separate words in some data structure that I haven't decided upon yet.
My first thought would be to use
getline(cin, trash, '_');
three times and deal with the data that follows, but then how would I loop line by line until the end of the input?
You basically have two options:
use getline for each line, then parse it
use getline(stream, string) to get a line from your stream, and store it into a string. Then construct an istringstream to parse this again (with the getline you thought of.
get what you need, and then ignore() stuff unill the next newline
You do getline() thing, and then you call ignore() (doc)
to read and discard the rest of the line, so you can start again with the next line.
which one you use is up to you. but the second one has slightly better performance, if you care about that stuff.

Parsing a tab delimited text file

I'm trying to parse a text file from one format to another. The text file is delimited by tabs. The text file I'm using as test has as of now three types of lines. For example, the first line of the text file has an H in the beginning. Since I do not need it now, I ignore it and pass to the next line. Similarly, I have lines that start with S and L. The S lines have five strings, including the first character, which are read by:
while(std:: ifstream readFile >> string1 >> string2 >> string3)
Below this while I have an if statement to check every S at the beginning of each line, which is as follows:
if(string1[string1.length()-1]=='S')
Then I print in the console each value to make sure every line which has an S is being printed in the console, but it's not. It's showing n - 2 where n = total of lines containing S at the beginning. I should also mention that below print statement, I also have this: std::getline(readFile, string1); without this, it shows me n - 5, if I'm not mistaken.
Also, when I only use two parameters while instead of three, all lines are shown with the first two strings, but as soon as I pass three parameters it changes back to n - 2.
What could be the problem that whenever I pass more than two parameters, it does not show me every line that contain S at the beginning(specifically the first two).
Thanks, and sorry if not explicit enough.

How do you read a word in from a file in C++?

So I was feeling bored and decided I wanted to make a hangman game. I did an assignment like this back in high school when I first took C++. But this was before I even too geometry, so unfortunately I didn't do well in any way shape or form in it, and after the semester I trashed everything in a fit of rage.
I'm looking to make a txt document and just throw in a whole bunch of words
(ie:
test
love
hungery
flummuxed
discombobulated
pie
awkward
you
get
the
idea
)
So here's my question:
How do I get C++ to read a random word from the document?
I have a feeling #include<ctime> will be needed, as well as srand(time(0)); to get some kind of pseudorandom choice...but I haven't the foggiest on how to have a random word taken from a file...any suggestions?
Thanks ahead of time!
Here's a rough sketch, assuming that the words are separated by whitespaces (space, tab, newline, etc):
vector<string> words;
ifstream in("words.txt");
while(in) {
string word;
in >> word;
words.push_back(word);
}
string r=words[rand()%words.size()];
The operator >> used on a string will read 1 (white) space separated word from a stream.
So the question is do you want to read the file each time you pick a word or do you want to load the file into memory and then pick up the word from a memory structure. Without more information I can only guess.
Pick a Word from a file:
// Note a an ifstream is also an istream.
std::string pickWordFromAStream(std::istream& s,std::size_t pos)
{
std::istream_iterator<std::string> iter(s);
for(;pos;--pos)
{ ++iter;
}
// This code assumes that pos is smaller or equal to
// the number of words in the file
return *iter;
}
Load a file into memory:
void loadStreamIntoVector(std::istream& s,std::vector<std::string> words)
{
std::copy(std::istream_iterator<std::string>(s),
std::istream_iterator<std::string>(),
std::back_inserter(words)
);
}
Generating a random number should be easy enough. Assuming you only want psudo-random.
I would recommend creating a plain text file (.txt) in Notepad and using the standard C file APIs (fopen(), and fread()) to read from it. You can use fgets() to read each line one at a time.
Once you have your plain text file, just read each line into an array and then randomly choose an entry in the array using the method you've suggested above.