简体   繁体   中英

Printing output from a text file c++

This is the code I am using to print output from my textfile

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
string line[30];
ifstream myfile("input1.txt");
int a = 0;

if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}  
while(!myfile.eof())
{
getline(myfile,line[a],' ');
cout<<line1[a]<<"\n";

}
}

The text output is supposed to be:(Also the output is exactly the same as the input)

ABCDEFGHIJKLMNOPQRSTUVWXYZ

9876543210

MFCJABDEHGIKLTPNORSQWUVYXZ

SPHINCTERSAYSWHAT

524137968

MATLSO

FTERFO

EYBLEIF

LYBWIOL

SYGTHO

FPNOEDESO

LLTDREOI

But instead I get this output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

9876543210

MFCJABDEHGIKLTPNORSQWUVYXZ

SPHINCTERSAYSWHAT

524137968

MATLSO

(double space between these two)

FTERFO

(double space after this one)

EYBLEIF LYBWIOL(EYBLEIF on top and LYBWIOL directly under it with no new line)

SYGTHO FPNOEDESO LLTDREOI(all of these from top to bottom directly underneath each other)

From docs

 istream& getline (istream& is, string& str, char delim); Get line from stream into string Extracts characters from is and stores them into str until the delimitation character delim is found. 

It seems that you have two extra spaces after "MATLSO" and "FTERFO". Remove them.

UPDATE: "delimitation character" in your code is ' ' so "MATLSO " will be treated as several lines, not one.

The space is the delimiter for getting another line of text. So if you have trailing spaces at the end of lines in the input file you will get some additional blank lines in the output.

Sometimes it's useful to view your input file in a text editor and turn on control characters so that you can see any additional spaces at the end of lines. For example in VI editor I use "set list" to see control characters (line endings, tabs etc).

To help process your input file you might want to cleanse it (remove trailing spaces) before parsing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM