尝试使用 Ifstream 打开.txt文件时C++问题

C++ problem trying to open a .txt file using Ifstream

本文关键字:文件 C++ 问题 txt 打开 Ifstream      更新时间:2023-10-16

这一小段代码旨在查看文本文件并识别已经写入的帐号,以便稍后在我的程序中,您可以找到正确的帐户,而不会出现两个具有相同帐号(id(的帐户的错误。但是无论我做什么,无论是在 ifstream 对象的位置使用双反斜杠、正斜杠还是双正斜杠;我总是得到"找不到文件"作为输出。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream accountsread("‪G:/Coding/Test/test/test/accounts.txt");
if (accountsread.is_open()) {
int tempAccno;
std::string tempname;
char tempchar;
int accountsfound = 0;
int input;
std::cout << "Enter the ID of the account n";
cin >> x;
while (!accountsread.eof()) {
accountsread >> tempAccno;
if (tempAccno == input) {
accountsfound++;
}
else {}

}
if (accountsfound > 0) {
cout << "number found";
}
else {
cout << "number not found";
}
}
else {
cout << "cannot find file";
}
}

in windows, the location of the text file is ‪G:\Coding\Test\test\test\accounts.txt

std::ifstream可以使用相对路径和绝对路径。对于您的问题,如果您确实需要文件的绝对路径,我建议您查看 STL 中的<filesystem>标头。但是,如果它与工作目录位于同一目录中,则无需使用绝对路径。这是我完成任务的方法

#include <iostream>
#include <fstream>
#include <string>  // Should include since you're using std::string
// Note that I am NOT "using namespace std;"
int main()
{
std::ifstream accountsRead("accounts.txt");
if (accountsRead.is_open())
{
int account_id;
bool account_found = false;
std::cout << "Enter the ID of the account: ";
while (!(std::cin >> account_id))
{ // This loop handles if the user inputs non-number
std::cout << "Please enter a NUMBER below!n";
std::cout << "Enter: ";
std::cin.ignore(10000, 'n');
std::cin.clear();
}

int tmpAccNum;
while (accountsRead >> tmpAccNum)
{ // This loop reads the file, line by line, into tmpAccNum
if (tmpAccNum == account_id)
{
account_found = true;
break;
}
}
if (account_found)
{
std::cout << "Number found!" << std::endl;
}
else
{
std::cout << "Number not found..." << std::endl;
}
}
else
{ // Error opening file
std::cout << "File not found or is corrupted" << std::endl;
}
}

从风格上讲,关于代码的一些事情。首先,你永远不应该using namespace std,并且(如果你出于某种原因(没有理由只在某些std成员上混合和匹配指定std命名空间。其次,您不需要为每个if-语句指定一个else,除非在达到else情况时确实有要执行的命令,否则您可能不应该这样做。

编辑

如果您仍然需要绝对路径,您可以通过以下方式执行此操作:

#include <filesystem>
int main()
{
// Create path object for the file path
std::filesystem::path file_path("G:CodingTesttesttestaccounts.txt");
// The '.string()' method for a 'std::path' object returns the string
// version of the path, so you can use it with an 'std::ifstream'
std::ifstream accounts(file_path.string());  // Opens file via 'ifstream'
/* And so on... */
}