C ++迭代,文件i / o

时间:2013-04-04 15:10:39

标签: c++ file io iteration

#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.*

我不知道为什么。

1 个答案:

答案 0 :(得分:4)

这一行:

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

应该是:

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

您的+正在将i添加到字符串常量"line: ",这样可以在每次循环时将一个字符从前面敲掉(并最终离开结尾,导致未定义的行为)。

您无法以您尝试的方式在C ++中向字符串添加对象,但您可以通过重复使用cout将多个对象发送到<<

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

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

在这里:

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