'cout'未在此范围错误中声明
'cout' was not declared in this scope error
我正在尝试使用 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
选项进行编译。
相关文章:
- 错误:未在此范围内声明'reverse'
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 错误:"imread"未在此范围内声明
- 在气泡排序程序中未声明错误功能
- 使用全局声明的向量时,C++双重释放错误/损坏
- 使用直接大括号初始化时,C++ 编译错误"声明末尾的预期";"
- C++ [错误] 声明'char '隐藏参数。什么意思?
- 类中的静态函数给出了错误:声明中的两种或多个数据类型
- 错误:声明冲突 - 指针不能是 int
- 收到 CUDA 错误"声明与以前的"variable_name"不兼容
- 错误:声明不声明
- Visual Studio 2010 链接器错误C++声明我从头文件创建的类时
- Cython 错误:声明不声明任何内容
- 错误"声明非模板函数"C++
- 无效地使用不完整的类型/前向错误声明.可能误用抽象类?(c++)
- 错误:声明冲突.用c++编译c代码
- C++错误:声明中存在显式限定
- else语句(C++)上的错误w/声明
- 初始化const类成员,错误:声明没有声明任何内容