在C+中重新实现dos2unix和unix2dos+'\r';和'\n';没有出现在hextump中? 我试图在C++中重新实现代码> DOS2UNIX < /C>和 UNIX2DOS 。这是我的dos2unix: dos2unix 输出转储 预期输出的输出
为什么会发生这种情况?我在实现在C+中重新实现dos2unix和unix2dos+'\r';和'\n';没有出现在hextump中? 我试图在C++中重新实现代码> DOS2UNIX < /C>和 UNIX2DOS 。这是我的dos2unix: dos2unix 输出转储 预期输出的输出,c++,char,hex,C++,Char,Hex,为什么会发生这种情况?我在实现unix2dos时也会遇到类似的行为为了避免从输入中消除空白,最简单的更改就是使用is.get(c)而不是is>。作为一个未格式化的输入函数,将提供文件中所有内容的逐字符读取。运算符>提供消除空白的格式化输入 更改为istream。get()提供了您描述的行为 #include <iostream> #include <fstream> #include <string> int main(int argc, char** ar
unix2dos
时也会遇到类似的行为为了避免
从输入中消除空白,最简单的更改就是使用is.get(c)
而不是is>。作为一个未格式化的输入函数,将提供文件中所有内容的逐字符读取。运算符>
提供消除空白的格式化输入
更改为istream。get()
提供了您描述的行为
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char** argv) {
std::string fn {};
char c;
if (argc < 2) { /* validate filename provided */
std::cerr << "error: filename required.\n";
return 1;
}
fn = argv[1];
std::ifstream is (fn.c_str());
std::ofstream os ("temp.txt");
while (is.get(c))
if (c != '\r')
os.put(c);
string command = "mv temp.txt " + fn;
system(command.c_str());
}
示例使用/输出文件
$ cat dat/fleas2line.txt
my dog has fleas
my cat has none
您可以看到,“\n”
保存在您的输入中
$ hexdump -Cv temp.txt
00000000 6d 79 20 64 6f 67 20 68 61 73 20 66 6c 65 61 73 |my dog has fleas|
00000010 0a 6d 79 20 63 61 74 20 68 61 73 20 6e 6f 6e 65 |.my cat has none|
00000020 0a |.|
temp.txt
$ cat temp.txt
my dog has fleas
my cat has none
最后,避免在代码中使用0XD
和0XA
,而是使用字符本身,例如'\r'
和'\n'
。它使代码更具可读性。仔细检查一下,如果您还有其他问题,请告诉我。为了避免>
从您的输入中删除空白,最简单的更改就是使用is.get(c)
而不是is>>c
。作为一个未格式化的输入函数,将提供文件中所有内容的逐字符读取。运算符>
提供消除空白的格式化输入
更改为istream。get()
提供了您描述的行为
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char** argv) {
std::string fn {};
char c;
if (argc < 2) { /* validate filename provided */
std::cerr << "error: filename required.\n";
return 1;
}
fn = argv[1];
std::ifstream is (fn.c_str());
std::ofstream os ("temp.txt");
while (is.get(c))
if (c != '\r')
os.put(c);
string command = "mv temp.txt " + fn;
system(command.c_str());
}
示例使用/输出文件
$ cat dat/fleas2line.txt
my dog has fleas
my cat has none
您可以看到,“\n”
保存在您的输入中
$ hexdump -Cv temp.txt
00000000 6d 79 20 64 6f 67 20 68 61 73 20 66 6c 65 61 73 |my dog has fleas|
00000010 0a 6d 79 20 63 61 74 20 68 61 73 20 6e 6f 6e 65 |.my cat has none|
00000020 0a |.|
temp.txt
$ cat temp.txt
my dog has fleas
my cat has none
最后,避免在代码中使用0XD
和0XA
,而是使用字符本身,例如'\r'
和'\n'
。它使代码更具可读性。仔细检查一下,如果您还有其他问题,请告诉我。您应该以二进制模式打开文件,以避免自动换行。使用is.get(c)
和os.put(c)
而不是
。还建议'\r'
和'\n'
而不是0XD
和0XA
。应以二进制模式打开文件,以避免自动换行。使用is.get(c)
和os.put(c)
而不是
。同时推荐'\r'
和'\n'
而不是0XD
和0XA
。谢谢!除了可读性之外,您是否建议远离十六进制并严格使用\r
和\n
?我想检查一个和它们一致的hextump会更容易。可读性就是它'\r'==0xd
和'\n'==0xa
,因此您可以自由使用任何您喜欢的。一般的共识是,当你指的是文字的时候,就使用文字。谢谢!除了可读性之外,您是否建议远离十六进制并严格使用\r
和\n
?我想检查一个和它们一致的hextump会更容易。可读性就是它'\r'==0xd
和'\n'==0xa
,因此您可以自由使用任何您喜欢的。一般的共识是,当你指的是文字时,使用文字字符。