从文件中发出读取变量

时间:2015-10-29 03:41:34

标签: c++

我的文件只有一行

" P00321 A 9"

我需要将每个变量作为3个单独的变量,但似乎没有用我的代码正确读取它们。

ifstream inFile;
int hours;
string accountnum;
char servicecode;

...

inFile.open("inputs.dat");
inFile >> accountnum >> servicecode >> hours;

如果我将这些帐号出现空白,则服务代码显示为带下划线的@符号,小时数为长十进制数字。
我做错了什么?

3 个答案:

答案 0 :(得分:0)

你保留了" inputs.dat"文件格式是否正确(即ANSI)?

答案 1 :(得分:0)

您是否尝试使用空格作为分隔符的strtokchar* strtok( char* str, const char* delim ); 将此调用三次以获得三个单独的变量。

答案 2 :(得分:0)

完美无缺

  • 检查文件路径
  • 检查程序云是否打开文件
  • 尝试运行此代码并检查结果

<强>码

#include <string>
#include <fstream>
#include <iostream>

int main()
{
    std::ifstream inFile;
    int hours;
    std::string accountnum;
    char servicecode;  

    inFile.open("E:\\input.dat");
    if (inFile.is_open())
    {
        inFile >> accountnum >> servicecode >> hours;
        std::cout << accountnum << std::endl;
        std::cout << servicecode << std::endl;
        std::cout << hours << std::endl;
    }
    std::cout << "cant open" << std::endl;
    system("pause");
    return 0;
}

文件

P00321 A 9