0

I'm making a program where you can login and register. All the data is stored in a .txt file. The problem that I currently have is that when I try to get all the data from the file, I only get the first line/string of the file. I want to get everything in the .txt. Here is some code:

What's in the .txt:

hello:world
foo:bar
usr:pass

Code (as a test):

ifstream check;
check.open("UsrInfo.txt");

string dataStr;
getline(check, dataStr);

cout << dataStr;
cout << endl;

Output:

hello:world

What I want the output to be:

hello:world
foo:bar
usr:pass

What can I do to fix this? Thanks!

Archie Gertsman
  • 1,459
  • 2
  • 14
  • 37
  • Possible duplicate of [Read file line by line](http://stackoverflow.com/questions/7868936/read-file-line-by-line) – awesoon Nov 08 '15 at 05:27
  • 1
    `I only get the first line` Have you considered repeating the very same operation for other lines? [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) might be of help. – Ivan Aksamentov - Drop Nov 08 '15 at 05:29

2 Answers2

5

You would need to put it through a loop and read line by line

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

    int main () {
     string line;
     ifstream check ("example.txt");
     if (check.is_open())
     {
       while ( getline (check,line) )
       {
         cout << line << '\n';
       }
       check.close();
     }

    else cout << "Unable to open file"; 

    return 0;
    }
0xtvarun
  • 688
  • 6
  • 18
-1

getline gets one line, if you would like more then one line try this;

std::string Line, Result;
while (true){
  getline(check, Line);
  if (!check.eof())
    Result.append(Line), Result.push_back('\n');
  else
    break;
}
user4578093
  • 221
  • 1
  • 2
  • 10
  • [While not eof almost never works](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) and won't here. The comma operator is almost certainly not what you want to use here. Should work, but a really bad coding style not worth teaching or emulating because of the number of ways comma misuse can silently torpedo a program. Just use a semicolon. – user4581301 Nov 08 '15 at 09:28
  • Do you think this'll fix it? – user4578093 Nov 12 '15 at 09:14
  • 1
    Recommend `while (getline(check, Line))` instead of `while (true)`. `getline` returns a reference to the iostream used, and iostream implements a boolean operator that returns true if the stream is readable and not in an error state. `Result.append(Line), Result.push_back('\n');` gains nothing from the ','. Go for clarity and use a ';', or `Result.append(Line + "\n");` – user4581301 Nov 12 '15 at 19:11