'cout'未在此范围错误中声明

'cout' was not declared in this scope error

本文关键字:错误 声明 范围 cout      更新时间:2023-10-16

我正在尝试使用 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);
}
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("");
}
vector<string> theText;

声明一个空向量。

theText[i] = line;

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

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

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

因此,即使您访问向量中不存在的元素(索引越界(,也不会有任何错误(除非可能是段错误......

你应该使用std::vector::push_back将元素添加到向量:

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

撇开问题不谈:

您可以从最后一个循环中删除&& !it->empty(),这是没有用的。如果向量为空begin()则返回end()并且代码永远不会进入循环。

thetext向量使用 push_back

您正在为空向量编制索引

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

同时从 for 循环中删除!it->empty()

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

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