reading a text file in C++ displays no output [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am very new to C++ i have this code which is supposed to print the text file in Task1 but it displays nothing and it gives me no output. and the text file contains "1 2 3 4" for an example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string line ;
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
getline( myfile, line );
//cout<<line.length();
while( getline( myfile, line ) )
{
for (int i=0; i < line.length(); i++)
{
cout<<line[i];
//if (line[i] ...) // look at each character and process it accordingly
}
}
getchar();
}
how can i fix this?

There is a simple issue with your code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string line ;
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
getline( myfile, line ); // That's the problematic line!
//cout<<line.length();
while( getline( myfile, line ) ) // first line lost here
...
You read the first (and presumably only line) of the file and simply discard it, because you enter the while loop immediately afterwards.
Fix: Remove the line getline( myfile, line ); that precedes the while loop.
You should also check that the file actually exists (there may be a typo in the filename!):
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
if ( !myfile )
{
std::cerr << "File does not exist!\n";
return 1;
}
If you aren't planning to use the fstream for output as well, just replace
std::fstream myfile("D:\\Task1.txt", std::ios_base::in);
by
std::ifstream myfile("D:\\Task1.txt");

You are ignoring first line by reading and do not outputting it.
string line ;
ifstream myfile("D:\\Task1.txt");
while(getline(myfile, line))
{
cout << line << endl;
}
Extra:
You don't need to use std namespace if you are using "using namespace std".
You can use ifstream to read-only.

Better You use ifstream for reading.
Check always an ifstream, whether the open was successful or not.
std::ifstream myfile("D:\\Task1.txt");
if( !myfile.is_open() ) {
cerr << "error open file\n";
// return or break
}
If You want to read numbers, so read numbers
for( int number; myfile >> number; ) {
cout << number << endl;
}

you need to flush the cout if you want the output printed. Change this line:
cout<<line[i] << std::endl;
and you will have the chars printed in a column

How many lines you have in text file?
You call getline twice before you start printing output. If you have only one line you'll get empty string ;)
Also I don't think your while condition is proper. Getline won't return anything useful anyway (it returns istream). If it approach end of file it'll simply rise error flag.
You should do it like that:
while (! myfile.eof() )
{
// do some reading & printing
}
Also, please, remember to close your file via myfile.close().
Hope it helps.

Related

C++ passing a file to a string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi i am trying to pass a whole file into a string. This is my Code but the program is always exiting on the first if(). I just can't get behind what i am doing wrong here.
#include <iostream>
#include <fstream>
#include <string>
std::string readFile (std::string filename);
int main() {
std::string filename;
std::string Eingabestring;
std::cout << "Geben Sie eine Datei an" << std::endl;
std::cin >> filename;
Eingabestring = readFile(filename);
std::cout << Eingabestring << std::endl;
return 0;
}
std::string readFile (std::string filename)
{
std::string zeile,inhalt ;
std::ifstream quelle;
quelle.open(filename.c_str());
if (!quelle)
{
std::cerr << filename << " kann nicht geƶffnet werden!\n";
return exit(-1);
}
while (!quelle.eof())
{
getline(quelle,zeile);
inhalt = inhalt + zeile;
}
return inhalt;
}
Already thanks for your help!
Edit: I just noticed that i put the file into a wrong folder.. But the code still isn't reading the whole file. Just the first line, but i thought with the loop i could get every line of my file into the string?
And i fixed the second return 0 to exit(-1). Thats better right?
Other than checking to see why the open() failed as explained in the comments also keep in mind that there are easier ways to check for when you have hit the end of file in a while loop where you are reading from an istream.
The idiomatic way to loop and read from an istream in C++ is to embed the read expression that returns a reference to the istream in the loop condition, so change your code to
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main() {
auto character = char{};
auto file_string = string{};
while (cin.get(character)) {
file_string += character;
}
cout << file_string << endl;
return 0;
}
I've used cin above but just replace cin with your file stream object and everything should work normally.
Note that the while terminating condition is now an istream reference, and that is convertible to bool, so the loop will exit when the istream object is done reading or when the stream encounters any errors besides EOF. You don't have to check for eof() yourself.
Also another thing is to pass strings that you do not intend to modify by const reference instead of by value, so the readFile() function should accept a const string& instead of a string, this will help save you string copying. When C++17 is available replace that const string& with std::string_view
Try something like this to read your file instead:
std::string readFile (std::string filename)
{
std::ifstream quelle(filename);
std::string content( (std::istreambuf_iterator<char>(quelle) ),
(std::istreambuf_iterator<char>()) );
return content;
}

C++ read from file and know if stream is string or numeric [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I've a file like this
A 2 3 4 6
B 10 1 2 6
and when I read it I need to check if I read a character or a number. But I've no idea how...
string fileName = "/Users/Fry/Desktop/file/file/file.txt";
ifstream myReadFile;
myReadFile.open(fileName);
char output[1000];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
myReadFile >> output;
cout << output << endl;
}
}
You can use standard C function std::isdigit declared in header <cctype> that to check whether the first character (or each character) of the read string is a digit and if so then apply C++ function std::stoi
For example
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
//...
std::string fileName = "/Users/Fry/Desktop/file/file/file.txt";
std::ifstream myReadFile( fileName );
std::string data;
while ( myReadFile >> data )
{
if ( std::isdigit( data[0] ) )
{
std::cout << "It is number " << std::stoi( data ) << std::endl;
}
else
{
std::cout << "It is string " << data << std::endl;
}
}
You can parse the file string by string, and check whether each small string is a number or not. Something like:
#include <fstream>
#include <cctype>
#include <sstream>
...
std::string tmp;
while (myReadFile >> tmp){
// you got a string...
if (is_number(tmp)){
// it's a number
}
else{
// it's not a number
}
}
To check whether a string is a number or not, you can use the following function, which is be able to handle multiple-char number like 10 or non-numbers like 123abc45.
bool is_number(const std::string& s){
return !s.empty() && s.find_first_not_of("0123456789") == std::string::npos;
}
Include <cctype> and use isdigit() and isalpha() to check the characters read.
I'm not sure if it's relevant in this case; it looks to me like
you have a very fixed format, and can know exactly whether you
should expect a letter or a number. But otherwise, you can
always peek ahead:
myFile >> std::skipws; // Since we're going to use unformatted input
if ( std::isalpha( myFile.peek() ) ) {
// It's a letter, extract it into a char or a string
} else {
// It's (hopefully) a number, extract it into an int
}
std::istream::peek does not extract the character, so it is
still there for the normal formatted extractors. And it returns
an int (not a char) in the correct range for the functions
in <cctype>, so you don't have to worry about the undefined
behavior that results when calling them with a char.
Also, you shouldn't be using the results of >> before checking
to see that it succeeded, and you shouldn't use eof() as
a condition for a loop.

How to append text after a certain line number? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Say I have a text file containing 10 lines. I want to move to line #5, clear everything below it, and append some new texts after that. What is the most compact way to achieve this using C++ of stream (just in case I missed some ofstream features)?
Read N lines while writing to a second file, then write all the new text to the new file after that.
Use IOstream to open the file and store the first five lines in an array and recreate the test file using the array and whatever other lines you want. Here is a code example:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
const int linesToRead = 5; //How many lines to read before stopping
string lines [linesToRead];
int line = 0;
ifstream myinputfile ("example.txt");
if (myinputfile.is_open())
{
while ( myinputfile.good() && line<=linesToRead )
{
if(line<linesToRead)
{ //Stop reading at line 5
getline (myinputfile,lines[line]);
cout << lines[line];
}
line++;
}
myinputfile.close();
}
else cout << "Unable to open file";
//Begin creating new file
const int numberOfNewLines = 7;
string newlines[numberOfNewLines] = {"These", "are", "some", "of", "the", "new", "lines"}; //lines to be added after the previous 5
ofstream myoutputfile ("example.txt");
if (myoutputfile.is_open())
{
for(int i = 0; i<linesToRead; i++){
myoutputfile << lines[i] << "\n";
}
for(int i = 0; i<numberOfNewLines; i++){
myoutputfile << newlines[i] << "\n";
}
myoutputfile.close();
}
else cout << "Unable to open file";
return 0;
}

Opening File in C++ - getline fails on second iteration [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I cannot figure out why getline is working in one X-Code project but not in another. The error "No matching function for call to 'getline'.
When I make a single cpp file it compiles with no issues.
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I would really appreciate some assistance. I am just learning and the example above came from my test book.
The code is noisy and incorrect. The correct standard idiom is like this:
#include <fstream> // for std::ifstream
#include <string> // for std::getline and std::string
std::ifstream myfile("example.txt");
if (!myfile) { /* error, die */ }
for (std::string line; std::getline(myfile, line); )
{
std::cout << "Read one line: '" << line << "'\n";
}
Correctness:
You must check the success of the input operation before consuming the input. To do otherwise may be UB, and certainly never correct.
[Thanks #James for pointing this out:] good() doesn't check if a file was opened. You could use either !myfile.fail() or myfile.is_open(), but just don't bother (see below).
Noise:
The ifstream constructor takes the filename and opens the file already. Use it.
The ifstream cleans up in its destructor, no need to do that explicitly. Use tight scoping to close the file as soon as you're done with it.
Don't leak line into the ambient scope if you don't need it.
No need for good() (or any of the correct alternatives). Just evaluate the ifstream object in a boolean context to see if the file was opened successfully.
There is one actual error: you use the results of getline
without testing whether it has succeeded. The usual way of
writing your inner loop would be:
std::string line;
while ( std::getline( myfile, line ) ) {
std::cout << line << std::endl;
}
Others are more question of style, although some issues do
enjoy almost universal consensus: don't define a variable
before you need it, for example (and thus, the definition of
line should be immediately before the loop). Error output
goes to std::cerr, not std::out. And in case of an error,
you should returnEXIT_FAILURE, and not0`.
It's also generally accepted that you don't have to explicitly
close input (since the destructor will take care of it, and
you've already successfully read everything). The consensus
isn't as complete for others: I would never use using namespace
std;, for example, and I would never put the code following an
else on the same line. I also find code more readable if the
shorter condition in an if...else is the first, so I'd write:
if ( !myfile.is_open() ) {
std::cout << "Unable to open file" << std::endl
returnCode = EXIT_FAILURE;
} else {
std::string line;
while ( std::getline( myfile, line ) ) {
std::cout << line << std::endl;
}
returnCode = EXIT_SUCCESS;
}
Except that for anything more complicated, I'd factor the
processing of the file out into a separate function. So I'd end
up with something like:
if ( myfile.is_open() ) {
process( myfile );
} else {
// error handling...
}
But you seem to suggest that you're having problems with
std::getline in code you don't post. There are two obvious
possible explinations: you didn't include <string>, or you
forgot the std:: in front of it. There are other possible
explinations, but we'd have to actually see the code which is
failing to say exactly what is wrong.

How do I read a text file from the second line using fstream?

How can I make my std::fstream object start reading a text file from the second line?
Use getline() to read the first line, then begin reading the rest of the stream.
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
...
(Changed to std::getline (thanks dalle.myopenid.com))
You could use the ignore feature of the stream:
ifstream stream("filename.txt");
// Get and drop a line
stream.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
// Get and store a line for processing.
// std::getline() has a third parameter the defaults to '\n' as the line
// delimiter.
std::string line;
std::getline(stream,line);
std::string word;
stream >> word; // Reads one space separated word from the stream.
A common mistake for reading a file:
while( someStream.good() ) // !someStream.eof()
{
getline( someStream, line );
cout << line << endl;
}
This fails because: When reading the last line it does not read the EOF marker. So the stream is still good, but there is no more data left in the stream to read. So the loop is re-entered. std::getline() then attempts to read another line from someStream and fails, but still write a line to std::cout.
Simple solution:
while( someStream ) // Same as someStream.good()
{
getline( someStream, line );
if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true
{
// Only write to cout if the getline did not fail.
cout << line << endl;
}
}
Correct Solution:
while(getline( someStream, line ))
{
// Loop only entered if reading a line from somestream is OK.
// Note: getline() returns a stream reference. This is automatically cast
// to boolean for the test. streams have a cast to bool operator that checks
// good()
cout << line << endl;
}
The more efficient way is ignoring strings with std::istream::ignore
for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){
if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\n'))){
//just skipping the line
} else
return HandleReadingLineError(addressesFile, currLineNumber);
}
HandleReadingLineError is not standart but hand-made, of course.
The first parameter is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit:
Link at cplusplus.com: std::istream::ignore
If you are going to skip a lot of lines you definitely should use it instead of getline: when i needed to skip 100000 lines in my file it took about a second in opposite to 22 seconds with getline.
Call getline() once to throw away the first line
There are other methods, but the problem is this, you don't know how long the first line will be do you? So you can't skip it till you know where that first '\n' is. If however you did know how long the first line was going to be, you could simply seek past it, then begin reading, this would be faster.
So to do it the first way would look something like:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
// Open your file
ifstream someStream( "textFile.txt" );
// Set up a place to store our data read from the file
string line;
// Read and throw away the first line simply by doing
// nothing with it and reading again
getline( someStream, line );
// Now begin your useful code
while( !someStream.eof() ) {
// This will just over write the first line read
getline( someStream, line );
cout << line << endl;
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string textString;
string anotherString;
ifstream textFile;
textFile.open("TextFile.txt");
if (textFile.is_open()) {
while (getline(textFile, textString)){
anotherString = anotherString + textString;
}
}
std::cout << anotherString;
textFile.close();
return 0;
}
this code can read file from your specified line from file but you have to make file in file explorer before hand my file name is "temp" code is given below
https://i.stack.imgur.com/OTrsj.png
hope this can help
You can use ignore function as follow:
fstream dataFile("file.txt");
dataFile.ignore(1, '\n'); // ignore one line
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char buffer[256];
ifstream myfile ("test.txt");
// first line
myfile.getline (buffer,100);
// the rest
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}