【问题标题】:How to copy words from .txt file into an array. Then print each word on a separate line如何将 .txt 文件中的单词复制到数组中。然后在单独的行上打印每个单词
【发布时间】:2015-09-19 16:53:19
【问题描述】:

目标是从名为“words.txt”的文件中读取一组字符串,并将每个单词保存到数组字符串中。但是,我无法将单词保存并打印到控制台。我认为问题出在我的 GetStrings 函数中,但我不知道为什么。调用 PrintStrings 函数时,控制台不会打印任何内容。这让我觉得要么没有任何东西保存到数组中,要么打印功能不正确。

int main ()
{
    int count = 0;
    string strings [MAXSTRINGS];
    GetStrings(strings);
    // cout << strings[1];
    PrintStrings(strings, count);
    return 0;
}

int GetStrings (string S [])
{
    ifstream input ("words.txt");
    int count = 0;
    while (input >> S[count])
    {
        count++;
    }
    input.close ();
    return 0;
}

void PrintStrings (string S [], int C)
{
    int w = 0;
    while (w < C)
    {
        cout << S[w] << endl;
        w++;
    }
}

【问题讨论】:

  • 你的数组不是 MAXSTRINGS!这就是数组的长度。您的数组名为strings
  • 投票结束此问题为:寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及必要的最短代码在问题本身中重现它。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example
  • 哎呀,我错了!
  • 这还不错。不好的部分是你没有描述哪里出了问题,你试图解决什么,以及你认为哪里出了问题!如果您描述了这一点,人们将能够帮助您。
  • 好的,我会尝试更详细地了解具体的问题。

标签: c++ arrays string console


【解决方案1】:

问题是局部变量。函数内部声明的变量不能被其他函数使用:

int GetStrings (string S [])
{
    ifstream input ("words.txt");
/* --> */    int count = 0;

这里是使用它的地方:

PrintStrings(strings, count);

函数GetStrings 中的变量countmain 中的变量不同。

如果您希望函数修改外部(函数)变量,请通过引用传递:

  int GetStrings (string S [], int& count)

我建议将数组换成std::vectorstd::vector 保持其计数,您可以使用 std::vector::size() 访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2015-07-30
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多