![](/img/trans.png)
[英]C++ reading from a text file into a array and then into another text file
[英]reading from a text file to array in c++?
我試圖從文本文件中讀取每一行並放入數組列,我真的試過這個:
string buffer[256];
string a;
ifstream myfile ("1.txt");
for(i=0;i<10000;i++)
{
//readArrivalTimes(i);
myfile.getline (buffer,100);
a[i]=buffer;
}
但它沒有用
所以我嘗試了你給我的一個解決方案,我這樣做了:
std::vector<std::string> v;
std::string buffer;
string a[1024];
ifstream myfile;
myfile.open("1.txt");
for(i=0;i<n;i++)
{
getline (myfile, buffer);
a[i]= buffer;
cout << buffer << "\n";
}
但是我們可以看到它的字符串!
我們可以讓它作為整數運行嗎?
[解決了 :)]
首先感謝大家幫助我,我真的很感謝你的幫助,我是一個全新的c ++。
而且肯定不是作業。
我對代碼做了一些修改,因此可以使用整數
int a[1024];
ifstream myfile;
myfile.open("1.txt");
for(i=0;i<n;i++)
{
getline (myfile, buffer);
a[i]= atoi(buffer.c_str());
cout << buffer << "\n";
}
非常感謝你。
您的代碼中存在許多錯誤。
已經提到了一些,因為將char *分配給int數組。
但是你的方法比C ++更多的是C語言。 在C ++中,它看起來更像是這樣的:
std::vector<std::string> lines;
std::ifstream myfile("1.txt");
if(myfile.isopen())
{
std::string line;
while(getline(myfile, line))
{
lines.push_back(line);
}
}
我沒有測試它,但它應該告訴你如何做到這一點。
編輯:根據評論更改代碼。
再次編輯以使其適用於整數:
std::vector<int> numbers;
std::ifstream myfile("1.txt");
if(myfile.isopen())
{
std::string line;
while(getline(myfile, line))
{
int number;
std::istringstream(line) >> number;
numbers.push_back(number);
}
}
a
是一個字符串,它是一組字符的抽象。
a[i]
將返回對個別角色的引用。
buffer
是一個字符數組。 C / C ++約定,即數組名稱指向指向其第一個元素的指針。
所以,你在循環中所做的是將a的ith
元素分配給緩沖區開頭的地址,這幾乎肯定不是你想要做的。
你想要做的就是制作一個字符串數組; 即替換
string a;
同
string a[10000];
您的代碼中還有其他要解決的問題; 例如,如果您的文件有<10k行怎么辦?
int a[1024];
ifstream myfile;
myfile.open("1.txt");
for(i=0;i<n;i++)
{
getline (myfile, buffer);
a[i]= atoi(buffer.c_str());
cout << buffer << "\n";
}
這是正確的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.