[英]Populating 2D char array from text file with varying line length
我正在嘗試從如下文本文件填充2D char數組:
Bob
Jill
Mike
Steven
而且我不確定如何在每一行中使用不同長度的字符來執行此操作。 這是我的代碼:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
char names[4][7];
string fileName = "names.txt";
ifstream inFile(fileName);
while(!inFile.eof()){
for(int i=0; i<4; i++){
for(int j=0; j<7; j++){
inFile.get(names[i][j]);
}
}
}
for(int i=0; i<4; i++){
for(int j=0; j<7; j++){
cout << names[i][j];
}
}
return 0;
}
這將打印
Bob
Jill
Mike
Steven????????
每個在哪里? 只是個胡言亂語。 我很確定這是因為文本文件的每一行都不是7個字符長,因此它正在嘗試填充數組的其余部分。 正確的方法是什么? 我以為while(!inFile.eof()){}
會阻止這種情況。
由於您使用的是C ++,因此需要使用string
和vector
。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream file("file");
string line;
vector<string> names;
if (file.is_open())
while (getline(file, line))
names.push_back(line);
for (auto it = names.begin(); it != names.end(); ++it)
cout << *it << '\n';
return 0;
}
您可以通過在此處添加括號來突出顯示C數組和固定循環大小的問題:
for(int i=0; i<4; i++){
std::cout << '{';
for(int j=0; j<7; j++){
cout << names[i][j];
}
std::cout << '}';
}
將打印:
{Bob
Jil}{l
Mike
}{Steven<garbage>}{<garbage>}
確實,您的姓名存儲方式如下:
char names[4][7] {
{'B', 'o', 'b','\n', 'J', 'i', 'l'},
{'l','\n', 'M', 'i', 'k', 'e','\n'},
{'S', 't', 'e', 'v', 'e', 'n', <garbage>},
{<garbage>}
};
請參閱stackptr的答案進行更正。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.