gpt4 book ai didi

C++ 迭代,文件 i/o

转载 作者:行者123 更新时间:2023-11-27 23:16:54 25 4
gpt4 key购买 nike

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdlib.h>

using namespace std;

int main()
{
//Input .txt file
ifstream inputFile ("input.txt");

try
{
int i = 1; //Line iterator
int vertices = 0;
int faces = 0;

string line;
while (getline(inputFile, line))
{
//Take number from line 4, set as variable "vertices"
if (i == 3)
{
getline (inputFile,line);
size_t last_index = line.find_last_not_of("0123456789");
string str = line.substr(last_index);
vertices = atoi(str.c_str()); //Convert to int
cout << "vertices " + str << endl;
}

//Take number from line 11, set as variable "triangles"
if (i == 11)
{
getline (inputFile,line);
size_t last_index = line.find_last_not_of("0123456789");
string str = line.substr(last_index);
faces = atoi(str.c_str()); //Convert to int
cout << "faces " + str << endl;
}

if (i == 13)
{
i++;
break;
}

cout << "line: " + i << endl; //Prints line number
i++;

}
} catch(const char* error) {
cout << "Cannot read file, please try again." << error;
}

return 0;
}

这个程序只是试图读取文件,从几行中取出一个数字,并为每一行打印“行:”以及相应的行号。看起来 C++ 的迭代方式与 Java 不同?由于某种原因,该程序输出:

*ine: 
ne:
vertices 752
e:
:

Cannot read mesh, please try again.
faces r
annot read mesh, please try again.
nnot read mesh, please try again.*

我不知道为什么。

最佳答案

这一行:

cout << "line: " + i << endl;

应该是:

cout << "line: " << i << endl;

你的 +正在添加 i到字符串常量 "line: " ,其效果是每次在循环中将一个字符从前面敲掉(并最终离开结尾,导致未定义的行为)。

您不能按照您尝试的方式将对象添加到 C++ 中的字符串,但您可以将多个对象发送到 cout通过重复使用 << .

然后你在这里遇到同样的问题:

cout << "vertices " + str << endl;

这里:

cout << "faces " + str << endl;

关于C++ 迭代,文件 i/o,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15815074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com