【问题标题】:Reading words and storing them into an array读取单词并将它们存储到数组中
【发布时间】:2015-03-10 19:12:06
【问题描述】:

所以我目前有一个工作程序,可以成功找到并显示文本文件中的所有字符。我现在希望能够读取整个单词而不是字符,然后想将每个单词存储到一个数组中,但我什至不知道如何读取整个单词。

我当前的字符代码

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream infile("input.txt");

    if (!infile)
    {
        cout << "ERROR: ";
        cout << "Can't open input file\n";
    }

    infile >> noskipws;
    while (!infile.eof())
    {
        char ch;
        infile >> ch;

        // Useful to check that the read isn't the end of file
        // - this stops an extra character being output at the end of the loop
        if (!infile.eof())
        {
            cout << ch << endl;
        }
    }
    system("pause");
}

【问题讨论】:

  • 可以将&gt;&gt; 改为char,而不是将&gt;&gt; 改为std::string
  • 请阅读此声明的链接:while (!infile.eof())

标签: c++


【解决方案1】:

我现在希望能够读取整个单词而不是字符,然后想将每个单词存储到一个数组中,但我什至不知道如何读取整个单词

std::string word;
infile >> word;

【讨论】:

    【解决方案2】:

    ch 的类型更改为std::string,以便&gt;&gt; 将读取单词。

    【讨论】:

      【解决方案3】:

      使用,

      std::string word;
      infile >> word;
      

      而不是,

      char ch;
      infile >> ch;
      

      【讨论】:

        猜你喜欢
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-09
        • 2021-12-08
        • 1970-01-01
        • 2019-07-03
        相关资源
        最近更新 更多