[英]C++ Read from file and assign to a variables
我有個問題。 我有一個格式如下的文件:
A B
C D
E F
X Y
X2 Y2
X3 Y3
我知道如何分配A,B,C,D,E,F,X,Y(我檢查的每個文件都有此數據),但有時我有更多數據,例如X2 Y2,X3,Y3,我也想將它們關聯起來(無需事先知道文件中有多少個)。
實際上我的代碼如下所示:
reading >> a >> b >> c >> d >> e >> f >> x >> y;
你可以幫幫我嗎? 謝謝
使用向量的此解決方案可能會解決以下問題:
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <fstream>
using namespace std;
void getItems(vector<string>& v, string path)
{
ifstream is(path.c_str());
istream_iterator<string> start(is), end;
vector<string> items(start, end);
v = items;
}
int main()
{
vector<string> v;
getItems(v, "C:\test.txt");
vector<string>::iterator it;
for (it = v.begin(); it != v.end(); it++)
cout << *it << endl;
return 0;
}
注意:這里我假設您的文件在C:\\ test.txt中
如果我對您的理解很好,則希望確保必須閱讀文件中的所有行。
通過以下代碼,我為我解決了這個問題:
std::ifstream file_reading( filename_path_.c_str(), std::ios::in );
if( file_reading ) {
std::string buffer;
unsigned int line_counter = 0;
while( std::getline( file_reading, buffer ) ) {
std::istringstream istr;
istr.str( buffer );
if( buffer.empty() )
break;
istr >> x_array[local_counter] >> y_array[local_counter];
line_counter++;
}
}
使用getline和while循環,您都會將文件中的所有行都保存到可調整大小的std :: vector中。 如果在下一行找不到更多數據,則指令中斷將退出。
您可以將它們全部輸入為字符串。 將標頭指定為#input並使用gets()函數輸入整個輸入。 然后處理字符串。 您可以通過忽略空格(“”)和換行(“ \\ n”)來區分數字。 希望這可以幫助!
如果您不知道文件中有多少數據,則值得使用WHILE循環,條件是執行while循環直到到達文件末尾。
這樣的東西(確保您包括:iostream,fstream和string):
int main () {
string line;
ifstream thefile ("test.txt");
if (thefile.is_open())
{
while (thefile.good() )
{
getline (thefile, line);
}
thefile.close();
}
else
{
cout << "Unable to open\n";
}
return 0;
}
您可以使用2D向量:
輸入:
1 2 3
4 5
6
7 8 9
碼:
int val;
string line;
ifstream myfile ("example.txt");
vector<vector<int> > LIST;
if (myfile.is_open())
{
while ( getline(myfile,line) )
{
vector<int> v;
istringstream IS(line);
while( IS >> val)
{
v.push_back(val);
}
LIST.push_back(v);
}
myfile.close();
}
for(int i=0; i<LIST.size(); i++)
{
for(int j=0; j<LIST[i].size(); j++)
{
cout << LIST[i][j] << " ";
}
cout << endl;
}
輸出:
1 2 3
4 5
6
7 8 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.