这是我的代码。
ifstream readFile;
readFile.open("voltages.txt");
if (readFile.fail( ) )
{
cout << "\nCould not open the file ... check to see if voltages.txt exists\n";
system("pause");
return;
}
string tempString = "";
//readFile.seekg(0, ios::beg);
int idx = 0;
if (readFile.is_open())
{
while ( readFile.good() )
{
getline(readFile,tempString);
cout << tempString << endl;
}
readFile.close();
}
如果我将Voltages.txt移至c:/,那么它工作正常,但我现在将它与我的.exe放在同一文件夹中,并且当我在cout << tempString << endl;处设置断点时;它显示为“”。如果可能的话,我想将其保留在 .exe 中。正如你所看到的,我尝试从头开始寻找,但没有成功。请帮助这个 C++ 菜鸟!谢谢!
最佳答案
这可能是因为您正在尝试读取本地文件,而程序需要从 C:/链接到该文件
您可以通过将 Voltages.txt
替换为 C:/pathToVoltages/Voltages.txt
来测试这一点
我建议通过执行以下操作将文件传递给您的可执行文件:
int main(int argc, char argv[]){
ifstream readFile;
readFile.open(argv[2]);
/*Rest of the code*/
这假设文件的路径是由您提供给程序的第一个参数给出的,如下所示:
./program pathToFile/voltages.txt
希望这有帮助
关于c++ - 在 C++ 中,打开包含值的 .txt 文件后,读取该文件会给出 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13487201/