[英]C++ reading from a text file into a array/string
這是我到目前為止的代碼。
我需要做的是從兩個不同的文本文件,矩陣A和矩陣B中讀取。
我可以這樣做但是對於我讀過的每個文本文件矩陣,它只能得到它
1 0 0
(所以基本上是第一行)實際上是Matrix A的整個文本文件
1 0 0
2 0 0
3 0 0
那么有誰知道我怎么做到這一點?
謝謝!
#include <iostream> //declaring variables
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;
cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file
if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}
好吧, getline
明顯得到一條線。
你應該逐行閱讀,直到文件結束,你可以用,例如:
while (getline(myfile, line))
out << line << endl;
這意味着:雖然有一行從myfile獲取,但將該行寫入輸出流。
你只讀一次,所以這不是一個奇跡。 您需要使用while或for循環來連續閱讀。 你會寫這樣的東西:
while (getline (myfile, line))
cout << line << endl;
這將是要編寫的整個代碼:
#include <iostream> //declaring variables
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;
cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file
if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
while (getline (myfile, line))
cout << line << endl;
}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
while (getline (myfile, line))
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}
使用getline
是最簡單的方法:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void read_file_line_by_line(){
ifstream file;
string line;
file.open("path_to_file");
while (getline (file, line))
cout << line << endl;
}
int main(){
read_file_line_by_line();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.