【发布时间】:2015-11-21 16:01:58
【问题描述】:
我在这里查找了类似的帖子,但似乎没有人为我的问题做这项工作。 我基本上是在尝试将 .txt 文件中的一系列单词放入一个向量中,然后打印每个值。例如,我们有 我喜欢赛车 em> 在 array.txt 中,我希望我的向量在位置 0 有“I”,在 1 有“love”,依此类推。不幸的是,代码不会访问“array.txt”,因此它永远不会执行 if 条件下的代码。 现在我听说使用 fstream 库应该可以正常工作,但是永远找不到该文件。我怀疑它不起作用,因为它找不到路径,但我从未在 C++ 中打开文件。另外,我没有将文件放在项目文件夹中的任何位置。
我已经尝试了一些更改:
- file.open("array.txt");
- 省略 file.close();
- 包括“C:\array.txt”; (前面有#)
- file.open("C:\array.txt")
如果这很重要,我正在使用 Windows 10。
#include <iostream>;
#include <string>;
#include <vector>;
#include <fstream>;
//#include <"C:\Users\Samer El-Hage\Documents">;
using namespace std;
void main(){
vector<string> v (10);
ifstream file;
file.open("C:\array.txt", ios::in);
if (file.is_open())
{
for (int i = 0; i < 3; i++)
{
file >> v[i];
}
file.close();
}
else cout << "Could not access file.";
for (int i = 0; i < 3; i++)
{
cout << v[i] << " ";
}
}
此代码打印“无法访问文件”。
【问题讨论】:
-
在
file.open语句中,使用C:\\array.txt- 见en.cppreference.com/w/cpp/language/escape -
使用正斜杠:
"C:/array.txt"、转义的反斜杠:"C:\\array.txt"或原始字符串文字:R"(C:\array.txt)"。此外,包含后还有不必要的分号。 (事实上,在将警告视为错误设置中,这不会编译!) -
顺便说一句,
main()函数返回 int。总是。查一下。
标签: c++ file text vector fstream