简体   繁体   中英

How to read a string from a file with getline in c++?

I have 2 voids(save and load). save writes in the file and load loads from file. The problem is that when I try to read from that file it only reads one word, even with getline.

Here's my code:

#include <iostream>
#include <windows.h>
#include <limits>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

float r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, puncte, rc1, rc2, rc3, rc4, rc5, rc6, rc7, rc8, rc9, rc10, var;
string q1, q2, q3, q4, q5, q6, q7, q8, q9, q10;

void save()
{
ofstream outfile;
outfile.open("C:\\Users\\Public\\IntrebariTest.txt");
outfile << q1 << " " << q2 << " " << q3 << " " << q4 << q5 << " " << q6 << " " << q7 << " " << q8 << " " << q9 << " " << q10 << rc1 << " " << rc2 << " " << rc3 << " " << rc4 << rc5 << " " << rc6 << " " << rc7 << " " << rc8 << " " << rc9 << " " << rc10;
outfile.close();
}
void load()
{
ifstream infile;
infile.open("C:\\Users\\Public\\IntrebariTest.txt");
infile.getline(cin, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10);
infile >> rc1 >> rc2 >> rc3 >> rc4 >> rc5 >> rc6 >> rc7 >> rc8 >> rc9 >> rc10;
infile.close();
}

So if anyone knows what causes the problem, please comment: Thanks! And the error is:

error: no matching function for call to 'std::basic_ifstream<char>::getline(std::istream&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&, std::__cxx11::string&)'|

Not

infile.getline(cin, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10);

but

getline(infile, q1);
getline(infile, q2);
getline(infile, q3);
getline(infile, q4);
getline(infile, q5);
getline(infile, q6);
getline(infile, q7);
getline(infile, q8);
getline(infile, q9);
getline(infile, q10);

Also if you are going to read lines then you need to output lines.

Not

outfile << q1 << " " << q2 << " " << q3 << " " << q4 << q5 << " " << q6 << " " << q7 << " " << q8 << " " << q9 << " " << q10 << rc1 << " " << rc2 << " " << rc3 << " " << rc4 << rc5 << " " << rc6 << " " << rc7 << " " << rc8 << " " << rc9 << " " << rc10;

but

outfile << q1 << "\n" << q2 << "\n" << q3 << "\n" << 
    q4 << "\n" << q5 << "\n" << q6 << "\n" << q7 << "\n" << 
    q8 << "\n" << q9 << "\n" << q10 << "\n" << 
    rc1 << " " << rc2 << " " << rc3 << " " << rc4 << " " << rc5 << " " << rc6 << " " << rc7 << " " << rc8 << " " << rc9 << " " << rc10;

Of course this much repetition in your code should be alerting you to the fact that there is a better way to do this.

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