0
#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;
}

该程序只是试图读取文件,从几行中获取一个数字,并为每一行打印“line:”以及相应的行号。看起来 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.*

我不知道为什么。

4

1 回答 1

4

这一行:

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

应该:

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

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

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

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

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

和这里:

cout << "faces " + str << endl;
于 2013-04-04T15:12:56.673 回答