3

我有点想知道我是不是疯了,但我向你发誓,这段代码输出笑脸作为 .name 值!这到底是怎么回事?到目前为止,它似乎只在值为 1 时才有效,其他任何东西都会正确给出错误。

我意识到代码有缺陷 -> 我不需要帮助。

#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <list>

using namespace std;
using namespace tr1;


struct CollectedData
{
public:
    string name;
    float grade;

};

int main()
{
    string line;
    list<CollectedData> AllData;
    int count;

    ifstream myFile("test_data.txt");
    if (myFile.fail()) {cout << "Error opening file"; return 0;}
    else
    {
        cout << "File opened... \n";
        while( getline(myFile, line) ) {
            CollectedData lineData;
            lineData.name = 1;
            lineData.grade = 2;
            AllData.push_back(lineData);
        }
    }

    cout << "\n\n File contents: \n";

    list<CollectedData>::iterator Iterator;
    for(Iterator = AllData.begin(); 
            Iterator != AllData.end();
            Iterator++)
    {
        cout << "\t" << (*Iterator).name << " - ";
        cout << "\t" << (*Iterator).grade << "\n";
    }


    getchar();
    return 1;
}

:-) http://img21.imageshack.us/img21/4600/capturekjc.jpg

我知道代码没用,
我想知道为什么它给了我笑脸而不是错误

安慰。. . 嘲弄

4

5 回答 5

9

我想知道为什么它给了我笑脸而不是错误

因为数据类型是string,并且 char0x01打印出笑脸。您可能用 ASCII 来分配值0x31,即1字符 。

于 2009-08-31T02:38:02.660 回答
8

笑脸是 ASCII 值为 1 的字符。不知道为什么,但显然你的编译器决定把它当作一个字符,所以你得到了笑脸。

于 2009-08-31T02:35:58.607 回答
6

你的问题在这里:

lineData.name = 1;
lineData.grade = 2;

我应该注意,您得到的符号是 ASCII 1(即,正是您将 lineData.name 设置为的符号)。

while( getline(myFile, line) )

您需要获取该行并对其进行解析,将一个适当的字符串插入到 lineData.name 中,并将一个整数插入到 lineData.grade 中。

于 2009-08-31T02:33:58.937 回答
3

该字符串被分配了一个字符值 (1),它恰好是 ASCII 字符集中的笑脸。

于 2009-08-31T02:37:46.980 回答
2

就像其他人所说的 name 是字符串类型,所以最好给它分配一个字符串:

lineData.name = "1";

反逗号会让编译器知道这个值是一个字符串,并且您将停止获得笑脸。

那说...

最酷的。漏洞。曾经。

于 2009-08-31T04:15:06.080 回答