如何从 .t​​xt 文件中获取数据?

How to take data from a .txt file?

我尝试编写一个小程序从 .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; 
}

这是 C++ 中的一个小示例,向您展示如何使用 fstream 打开文件,在我添加一个循环 while ( getline (myfile,line) ) 检查文件流是否有一行之后然后程序将打印它 cout << line << '\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;
}

ifstreamcout 都是 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; 
}