Reputation: 119
guys. I'm writing this small test program to read the text file from "EXAMPLE.txt" into my main program. At the output, I put "*" to displayed the data during the output is the data that I want to extract it out and locate into an array. Let say, in this test program the data that I wanted to extract is "JY9757AC", "AZ9107AC","GY9Z970C". But after that, I have did a try run and I faced this problem when comes to the output.
EXAMPLE.txt
ABC:JY9757AC
HDMI:AZ9107AC
SNOC:GY9Z970C
MAIN.CPP
main()
{
string output;
ifstream readExample;
readExample.open("EXAMPLE.txt");
while(readExample.eof())
{
getline(readExample,output,':');
cout << "* " << output <<endl;
}
}
OUTPUT
* ABC //while loop output the "ABC", which is the data that I don't want.
* JY9757AC
HDMI //it work's well, as what I expected and so and the SNOC below
* AZ9107AC
SNOC
* GY9Z970C
I have no any idea why is the "* ABC" is shown on the output, is there anything wrong with my logic. or I missed out something inside the while loop? Thank You in advance for helping to solve my code!
Upvotes: 0
Views: 432
Reputation: 5013
Output stores the first extraction from Example.txt and prints it followed by *. In the first iteration output = "ABC";
in the second iteration output = "JY9757AC";
. I have added a getline()
in the while loop that reads the unwanted part of the line. I also added a string[]
to store the extracted values in.
#include <fstream>
#include <string>
using namespace std;
int main()
{
string output, notWanted, stringArray[3];
int i = 0;
ifstream readExample;
readExample.open("EXAMPLE.txt");
while (!readExample.eof())
{
getline(readExample, notWanted, ':');
getline(readExample, output);
cout << "* " << output << endl;
stringArray[i++] = output;
}
cin.get();
return 0;
}
Upvotes: 0
Reputation: 2654
The delim
parameter for getline
replaces the default delimiter for new line which is "\n".
What you are currently getting as a "line" is:
ABC
JY9757AC\nHDMI
AZ9107AC\nSNOC
GY9Z970C
What you can do is more something like this (if your output like GY9Z970C) is fixed-size:
ssize_t len = getline(readExample,output,':');
cout << "* " << (char*)(output + (len - 8)) <<endl;
Upvotes: 1
Reputation: 4241
First, I assume the while
loop is while(!readExample.eof())
, otherwise there should be no output at all.
Second, to your question, the first getline(readExample,output,':');
read "ABC" into the output
, so at the next line it outputs * ABC
, which is exactly what you got. No surprise.
Upvotes: 0