【问题标题】:'cout' was not declared in this scope error'cout' 未在此范围错误中声明
【发布时间】:2013-08-19 21:28:58
【问题描述】:

我正在尝试使用 getline 从文件中读取行,然后显示每一行。但是,没有输出。输入文件是 lorem ipsum 虚拟文本,每个句子都有新行。这是我的代码:

#include <vector>
#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main() {

    string line;
    vector<string> theText;
    int i = 0;
    ifstream inFile("input.txt");

    if(!inFile)
        cout << "Error: invalid/missing input file." << endl;
    else {
        while(getline(inFile, line)) {
            theText[i] = line;
            theText[i+1] = "";
            i += 2;
        }

        //cout << theText[0] << endl;
        for (auto it = theText.begin(); it != theText.end() && !it->empty(); ++it)
            cout << *it << endl;
    }
    return (0);
}

【问题讨论】:

  • 另外,这篇文章的标题与您遇到的问题有什么关系..?
  • 那是因为我在做了一些研究之后没有编辑它然后遇到了一个不同的问题。我想知道为什么我没有得到任何输出。

标签: c++ ifstream getline


【解决方案1】:
vector<string> theText;
...
while(getline(inFile, line)) {
    theText[i] = line;
    theText[i+1] = "";
    i += 2;
}

第一行声明一个空向量。要向其中添加项目,您需要调用push_back(),而不是简单地分配给它的索引。分配给超出向量末尾的索引是非法的。

while(getline(inFile, line)) {
    theText.push_back(line);
    theText.push_back("");
}

【讨论】:

    【解决方案2】:
    vector<string> theText;
    

    声明一个空向量。

    theText[i] = line;
    

    尝试访问向量中不存在的元素。

    就像std::vector::operator[] 文档中所说的那样:

    返回对指定位置 pos 的元素的引用。 不执行边界检查。

    因此,即使您访问向量的不存在元素(索引超出范围),也不会出现任何错误(除非可能是段错误...)。

    您应该使用std::vector::push_back 向向量添加元素:

    while(getline(inFile, line)) {
        theText.push_back(line);
        theText.push_back("");
    }
    

    抛开问题:

    你可以从最后一个循环中删除&amp;&amp; !it-&gt;empty(),它没用。如果向量为空begin() 返回end() 并且代码永远不会进入循环。

    【讨论】:

      【解决方案3】:

      push_back 用作thetext 向量

      您正在对空向量进行索引

         while(getline(inFile, line)) {
      
              theText.push_back(line);
              theText.push_back("\n");
          }
      

      同时从 for 循环中删除 !it-&gt;empty()

          for (auto it = theText.begin(); it != theText.end() ; ++it)
              cout << *it << endl;
      

      使用-std=c++0x-std=c++11 选项编译。

      【讨论】:

        猜你喜欢
        • 2013-02-17
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-29
        • 1970-01-01
        • 2016-07-10
        相关资源
        最近更新 更多