【问题标题】:Unable to open file to array in C++无法在 C++ 中打开文件到数组
【发布时间】:2013-04-12 22:56:08
【问题描述】:

我正在尝试打开一个文件并将其内容读入几个数组。我找不到我做错了什么。我正在使用绝对路径。 输入文件如下所示:

Sam     100    23   210
Bob     1     2    12
Ted     300   300   100
Bill    223   300   221
James   234   123   212
Luke    123   222   111
Seth    1     2     3
Tim     222   300   180
Dan     222   111   211
Ben     100   100     2

这是我的代码:

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
string name;
ifstream inFile;
string bowlerNames[10];
int bowlerScores[10][3] = {0};


inFile.open("C:\\Users\Seth\Documents\bowlingData.txt");

if (inFile.is_open()) //Checking if the file can be opened
{

for (int i = 0; i < 10; i++)
{
    inFile  >> bowlerNames[i] 
            >> bowlerScores[i][0]
            >> bowlerScores[i][1]
            >> bowlerScores[i][2];
}

for (int i = 0; i < 10; i++)
{
    cout    << bowlerNames[i] 
            << bowlerScores[i][0]
            << bowlerScores[i][1]
            << bowlerScores[i][2];
}
}
else cout << "Unable to open file..." <<endl; //Gives that sentence if the file can't be opened

inFile.close();

cout << endl; //spacing
system("Pause");
return 0;
}

【问题讨论】:

  • 程序的输出是什么?
  • 我修复反斜杠问题(Thx Floris)之前的输出是“无法打开文件”:)

标签: arrays io


【解决方案1】:

所有反斜杠都必须是双反斜杠!

inFile.open("C:\\Users\\Seth\\Documents\\bowlingData.txt");

通过执行以下操作自行确认:

string fileName = "C:\\Users\\Seth\\Documents\\bowlingData.txt");
cout << fileName << endl;

【讨论】:

  • 这似乎可行。但是当我只有文件名时它为什么不打开(没有反斜杠)。据我所知,这两个文件都在同一个目录中。
  • 我无法回答“为什么我使用相对路径时它没有打开”的问题 - 信息不足,抱歉。不过,很高兴它像这样工作。
  • 我有 inFile.open("bowlingData.txt");但它没有打开,即使它们在同一个目录中。
  • 首先,我会查看this answer 并使用那里提供的方法来确认您确实是从您认为开始的目录开始...回复this question。希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
相关资源
最近更新 更多