【问题标题】:C++ getline errors using char arrays使用 char 数组的 C++ getline 错误
【发布时间】:2021-02-28 02:53:37
【问题描述】:

我不断收到一条错误消息,在 getline(Input, sentence) 上显示“错误:没有用于调用 'getline(std::ifstream&, char [100])'| 的匹配函数”。我可能会遗漏一些东西,我不确定。我要做的是从输入中读取整行并使用 getline 将其插入 char sentence[100] 中。我必须根据作业的要求使用 getline。提前谢谢你。

char uniqueWords[100][16] = {""};
int multipleWords = 0;
int theWords[100];
int totalWords = 0;
char sentence[100];
char delimit[] = " /.";


ifstream Input;
Input.open("input.txt");
if (!Input.is_open())
{
    cout << "Error Opening File";
    exit(EXIT_FAILURE);
}

ofstream Output;
Output.open("output.txt", std::ios_base::app);
if (!Output.is_open())
{
    cout << "Error Opening File";
    exit(EXIT_FAILURE);
}


char *p;

while(!Input.eof())
{
    getline(Input, sentence);
    p = strtok(sentence, delimit);
    while(p)
    {
        Output << p ;
        words(p, uniqueWords, theWords, multipleWords);   // a function for the assignment
        totalWords++;
        p = strtok(nullptr,delimit);
    }
    create << "." << endl;
}

【问题讨论】:

  • 当然。 getline (stream, std::string)std::string 作为参数。您想要stream.getline (char array, size)(例如Input.getline (sentence, sizeof sentence))为什么要使用字符数组而不是std::stringstd::vector&lt;std::string&gt;&gt; 进行存储?另见Why !.eof() inside a loop condition is always wrong.

标签: c++


【解决方案1】:

问题是您尝试使用std::getline 而不是std::basic_istream::getline。 (例如,您使用了错误的getline())您尝试使用的getline() 需要std::string 用于目标存储,而不是普通的旧字符数组。上面的第二种形式很高兴将一个字符数组及其大小用于目标存储。您可以使用:

    while (Input.getline(sentence, sizeof sentence))
    {
        p = strtok (sentence, delimit);
        while (p)
        {
            Output << p ;
            words (p, uniqueWords, theWords, multipleWords);   // a function for the assignment
            totalWords++;
            p = strtok(nullptr,delimit);
        }
        std::cout << ".\n";
    }

其他想法,看看Why !.eof() inside a loop condition is always wrong.。请注意,使用可作为输入函数返回的流状态来控制您的读取循环。另见Why is “using namespace std;” considered bad practice?

当您输出错误消息时,使用std::cerr 写入stderr 而不是stdout。例如:

    std::ifstream Input ("input.txt");
    if (!Input.is_open())
    {
        std::cerr << "Error Opening File.\n";
        exit (EXIT_FAILURE);
    }

除此之外,您应该真正使用std::string 来存储字符串,使用std::vector&lt;std::string&gt; 来存储字符串集合。您可以将每个字符串复制到一个字符数组中,以便使用strtok() 进行解析。如果您还有其他问题,请仔细查看并告诉我。

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2013-12-13
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多