【发布时间】:2019-12-02 21:03:37
【问题描述】:
这一小段代码旨在查看文本文件并识别已写入的帐号,以便稍后在我的程序中,您可以找到正确的帐户,而不会出现两个具有相同帐号的帐户的错误(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";
}
}
在windows中,文本文件的位置是G:\Coding\Test\test\test\accounts.txt
【问题讨论】:
-
在您的场景(Windows)中,转义的反斜杠 (\) 是路径分隔符。可能想在 cmd 提示符下验证文件。文件资源管理器可能很棘手,例如该文件可能被命名为 accounts.txt.txt,但如果文件扩展名被隐藏,您将看不到它。