我有一个整数表,例如:
1,10,100
0,1,2
3,4,5
我必须从文件中读取准确的一行,然后将其保存在动态数组中。这就是我尝试读取该行的方式,但我不知道如何保存在动态数组中。
fstream& Go2Line(fstream& file, unsigned int num){
file.seekg(ios::beg);
for(unsigned int i=0; i < num - 1; ++i)
file.ignore(numeric_limits<streamsize>::max(),'\n');
return file;}
int main(){
fstream file("testo.csv",ios_base::in);
if (!file)
cout << "Unable to open file file.csv\n";
else
{
int Number2Go = 1;
Go2Line(file, Number2Go);
if (!file)
cout << "Unable to reach line " << Number2Go << ".\n";
else
{
string line;
getline(file,line);
std::stringstream convertor(line);// I Don't know how continue from here
}
}
return 0;}
最佳答案
Go2Line可以简化,使其更易于阅读和调试
fstream& Go2Line(fstream& file, unsigned int num)
{
file.seekg(ios::beg);
while (num > 0) // keep going until no more lines
{
file.ignore(numeric_limits<streamsize>::max(),'\n');
--num; // saw a line. reduce number of lines remaining to see
}
return file;
}
我建议为您的早期程序使用大量空间。它的成本不高,而且很容易看到牙套排列整齐。当您更好地掌握语言后,再走捷径。但现在使用所有大括号,甚至是可选的大括号,将它们放在自己的行上以便于查看,并将它们排成一行以便您一眼就能看出哪些大括号匹配。
下一点利用 getline
的能力来使用不同于行尾的定界符。
std::stringstream convertor(line);
std::string token; // somewhere to put the comma separated value
int numtokens = 0;
while (std::getline(convertor, token, ',')
{
numtokens++;
}
现在我们知道我们需要多大的数组,我们可以构建数组并将数字存储在其中。在我们用 std::atoi
将它们转换成数字之后或类似的。
int * array = new int[numtokens];
int index = 0;
while (std::getline(convertor, token, ',')
{
//convert token into number with std::atoi or similar
array[index] = std::atoi(token);
}
稍后当您完成后,您需要将array
的内存归还。
delete[] array;
如果您忘记或发生意外事件并阻止您到达您delete[] array;
的位置,这会导致问题。
例如,如果输入行看起来像 10,20,SUCKER!,30
怎么办? std::atoi
不会喜欢尝试变成“笨蛋!”进入一个 int
并会抛出一个 exception .这可能会让您错过 delete
ing array
。
一个更快的方法是拧紧动态数组。这是C++!
std::stringstream convertor(line);
std::string token;
std::vector<int> array; // more on this later
while (std::getline(convertor, token, ',')
{
array.push_back(std::atoi(token));
}
您所有的号码现在都在 std::vector
中.它会自行调整大小以适应,因此您不必担心在存储数字之前计算行中数字的数量。它还处理自己的所有内存,因此当 std::atoi
因“SUCKER!”抛出异常时,vector
会清理困惑。
为了保持示例简单,我还遗漏了很多改进,祝编码愉快!
关于c++ - 从 C++ 中的 csv 文件中读取特定行的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33947778/