从getline传递字符串作为参数

时间:2016-10-20 21:31:42

标签: c++

我正在尝试逐行读取文件,然后将行的每个单词放入变量

#include <iostream>
#include <string>

#include <fstream>
#include "record.h"
using namespace std;

void handleline(string& line1, int a)
{
    //cout<<line1[]<<"\n";
}

int main()
{
    string line1[30];
    ifstream myfile("30+.in");
    int a = 0;
    if (!myfile) {
        cout << "Error opening output file" << endl;

        return -1;
    }
    while (!myfile.eof()) {
        getline(myfile, line1[a], '\n');

        handleline(line1, a);
    }
}

问题是我不能将该行作为参数传递给函数。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

看看这是否有帮助:

void handleline(string & line)
{
    //you have just the one line to work on in this implementation
}

...

while (!myfile.eof()) {
    getline(myfile, line1[a], '\n');

    handleline(line1[a]);

    a++; // you forgot to increment a in your code
}

答案 1 :(得分:0)

string line1[30];

定义了一个string的数组。

handleline(line1, a);

string的数组传递给handlelineline1会将(What is array decaying?)衰减为指向stringstring *的指针。不幸的是

void handleline(string& line1, int a)

需要引用string。一个string,而不是string的数组或指向string的指针。

由于handleline一次仅消耗一个string

void handleline(string& line)
{
    //cout<<line<<"\n";
}

似乎更合理。

将使用

调用它
int main()
{
    std::vector<string> line1; // replaced array with resizable array to prevent overflow
    ifstream myfile("30+.in");
    int a = 0;
    if (!myfile) {
        cout << "Error opening output file" << endl;

        return -1;
    }
    string temp; // declares a temporary holder
    while (getline(myfile, temp, '\n')) // reads file into holder. Note this replaces 
                                         // !myfile.eof(), which is a classic bug. 
                                         // More on that later.
    {
        handleline(temp); // consume the one string
        line1.push_back(temp); // store in resizable array if needed.
    }
}

Why is iostream::eof inside a loop condition considered wrong?