我试图编写一个小程序来从.txt文件中检索数据并在终端中显示它,但出现错误。 我不得不说我是Visual Studio的新手。直到现在我都在从事code:blocks
我尝试了错误代码中的建议,在开头添加了#include“ pch.h”,但仍然没有用。
错误代码为C1010(如果我构建的代码不带行#include“ pch.h”);如果我使用该行进行构建,则会收到多个错误代码:
"1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(10): error C2065: 'ifstream': undeclared identifier
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(10): error C2146: syntax error: missing ';' before identifier 'inFile'
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(10): error C2065: 'inFile': undeclared identifier
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(11): error C2065: 'inFile': undeclared identifier
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(11): warning C4129: 'B': unrecognized character escape sequence
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(11): warning C4129: 'D': unrecognized character escape sequence
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(14): error C2065: 'inFile': undeclared identifier
1>c:\users\bogdan\documents\c & c++ programs\writing and reading a txt file\writing and reading a txt file\writing and reading a txt file.cpp(15): error C2065: 'cout': undeclared identifier"
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
int main()
{
ifstream inFile;
inFile.open("C:\Users\Bogdan\Documents\UID.txt");
int x;
inFile >> x;
cout << x;
return 0;
}
答案 0 :(得分:1)
ifstream
和cout
都是std
命名空间的一部分。您不是using namespace std
,因此在引用它们时需要包括名称空间。您的代码的固定版本为:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream inFile;
inFile.open("C:\Users\Bogdan\Documents\UID.txt");
int x;
inFile >> x;
std::cout << x;
return 0;
}
答案 1 :(得分:0)
这是C ++中的一个小示例,向我展示了如何在我添加循环while(getline(myfile,line))之后,使用fstream打开文件,该循环检查文件流是否有一行,如果有一行,则程序将打印它cout <<行<<'\ n';如果没有,程序将退出。
#include <iostream>
#include <fstream>
#include <string>
int main () {
string line;
std::ifstream myfile ("/path/to/file.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
std::cout << line << std::endl;
}
myfile.close();
}
else std::cout << "Error unable to open file" << std::endl;
return 0;
}