Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 文件中的字符不正确_C++_Text Files_Iostream_Fstream_Cout_Ascii - Fatal编程技术网

C++ 文件中的字符不正确

C++ 文件中的字符不正确,c++,text-files,iostream,fstream,cout,ascii,C++,Text Files,Iostream,Fstream,Cout,Ascii,我有以下.txt文件: test.txt 1,2,5,6 通过命令行传递到一个小型C++程序中: ./test test.txt #include <iostream> #include <fstream> using namespace std; int main(int argc, char **argv) { int temp =0; ifstream file; file.open(argv[1]); while(!fil

我有以下.txt文件:

test.txt

1,2,5,6

通过命令行传递到一个小型C++程序中:

./test test.txt
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
    int temp =0;
    ifstream file;
    file.open(argv[1]);

    while(!file.eof())
    {
        temp=file.get();
            file.ignore(1,',');
        cout<<temp<<' ';
    }
    return 0;
}
资料来源如下:

./test test.txt
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
    int temp =0;
    ifstream file;
    file.open(argv[1]);

    while(!file.eof())
    {
        temp=file.get();
            file.ignore(1,',');
        cout<<temp<<' ';
    }
    return 0;
}
#包括
#包括
使用名称空间std;
int main(int argc,字符**argv)
{
内部温度=0;
ifstream文件;
打开(argv[1]);
而(!file.eof())
{
temp=file.get();
忽略(1,,);

cout49是数字49-48=1的ascii码

get()
为您提供一个字符(字符代码)

顺便说一下,
eof()
仅在读取尝试失败后才变为真,因此您显示的代码

while(!file.eof())
{
    temp=file.get();
        file.ignore(1,',');
    cout<<temp<<' ';
}

temp
是一个int。因此,将字符强制转换为int后,您会看到编码的ascii值。

这与您认为的不同:

while(!file.eof())
这一点已包含在中,因此我不会在回答中包含

尝试:


…取而代之。读入
char
而不是
int
也可以省去转换表示法的麻烦(ASCII值49是
1
,等等)。

记录在案,尽管这是第n个副本,但这段代码在惯用C++中的外观如下:

for (std::string line; std::getline(file, line); )
{
    std::istringstream iss(line);

    std::cout << "We read:";

    for (std::string n; std::getline(iss, line, ','); )
    {
        std::cout << " " << n;

        // now use e.g. std::stoi(n)
    }

    std::cout << "\n";
}
for(std::string行;std::getline(文件,行);)
{
标准::istringstream iss(线);
标准::cout
for (std::string line; std::getline(file, line); )
{
    std::istringstream iss(line);

    std::cout << "We read:";

    for (std::string n; std::getline(iss, line, ','); )
    {
        std::cout << " " << n;

        // now use e.g. std::stoi(n)
    }

    std::cout << "\n";
}