【问题标题】:cout won't print in function [closed]cout 不会在函数中打印 [关闭]
【发布时间】:2018-04-03 00:38:27
【问题描述】:

我对编程很陌生,所以这可能是一个对你们来说答案很明显的问题,我真的很难过,为什么 cout 在以下函数中不起作用?我已经包含了 iostream 标头,所以我假设它与它在函数中有关?

 int inputFileData(song musicLibrary[])
{
    char discard = ' ';
    int counter = 0, length = 0;
    ifstream inData;

    inData.open("songs.txt");

    if (!inData)
    {

        cout << "Error: No input file found " << endl;
        cout << "Program terminating..." << endl;
        return 1;
    }

    while (!inData.eof())
    {
        inData.getline(musicLibrary[counter].title, ARRAY_CONST, ';');
        inData.getline(musicLibrary[counter].artist, ARRAY_CONST, ';');
        inData >> musicLibrary[counter].durationMinutes;
        inData.get(discard);
        inData >> musicLibrary[counter].durationSeconds;
        inData.get(discard);
        inData.getline(musicLibrary[counter].album, ARRAY_CONST, '\n');

        length = strlen(musicLibrary[counter].album);

        if (length = 0)
        {
            cout << length << endl; //This cout object doesn't work in this function
            break;
        }

        else
            counter++;
    }

    return counter;
}

【问题讨论】:

  • if (length = 0) -- 使用==
  • 不要使用数组,使用 std::vector。不要使用 char 数组,使用 std::string。
  • 哦哇!我不敢相信我错过了 == :))。这是我的课堂项目之一,我们不能使用字符串类,我们还没有达到向量。

标签: c++ iostream cout


【解决方案1】:

if (length = 0) 应该是 if (length == 0)

【讨论】:

    【解决方案2】:

    详细阐述 Eli 的答案:

    if (length = 0)
    

    将值0 分配length,然后计算表达式。由于表达式返回0,因此条件的计算结果为false,您无需输入if 子句。

    改为使用if (length == 0)

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多