且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用命令行输入文件比读取文件.

更新时间:2023-11-28 12:55:22

1.我希望您在访问argv[2]之前先检查argc>2吗?

2.我怀疑" exe method1 [fileName] "行仅表示语法,因此表示可选参数的方括号实际上并不是按字面意思编写的!例如,如果您的应用程序名为"reader.exe",则以下任意一项将是有效的调用:

reader.exe method1
reader.exe method1 mydata.txt
reader.exe method1 myotherdata.txt

换句话说,不需要剥开" []括号,因为据认为没有!

3. ifstream :: operator>>()具有多个重载来处理各种内置类型,但是这些重载都不能覆盖char [100]类型.即使它们做到了,您***希望的是该运算符从文件中精确地读取 个100个字符,包括空格和制表符和换行符之类的控制字符,但不添加结尾0.结果,如果您尝试打印该字符串,在第100个字符之前看起来可能是合理的一半,但是随着打印功能继续通过char数组读取到缓冲区中,它变成了乱码! (直到最终遇到0个字符).

正如Richard指出的那样,您应该为此使用其他功能.此外,除非使用将缓冲区大小作为附加参数的函数,否则使用固定大小的缓冲区来读取未定义格式的文件是一个坏主意.这将使它们能够捕获过长的输入并防止写入缓冲区.
1. I hope you checked that argc>2 before accessing argv[2]?

2. I suspect that the line ''exe method1 [fileName]'' just indicates the syntax, and the square brackets that indicate an optional parameter are therefore not meant to be actually written literally! If, say, your application is called ''reader.exe'', then either of the following would be valid calls:

reader.exe method1
reader.exe method1 mydata.txt
reader.exe method1 myotherdata.txt

In other words, there is no need to ''strip off'' the [] brackets, as there are supposedly none!

3. ifstream::operator>>() has multiple overloads to deal with various built-in types, but none of these cover the type char[100]. Even if they did, the best you could hope for would be that this operator reads exactly 100 characters from the file, including whitespace and control characters such as tabs and linebreaks, but without adding a terminating 0. As a result, if you tried to print that string, it might look halfway reasonable until the 100th character, but then turn into a garbled mess as the print function continues to read into the buffer past the char array! (until it eventually encounters a 0 character).

As Richard already pointed out, you should use other functions for this. And besides it is a bad idea to use a fixed size buffer for reading from a file of undefined format unless you use functions that take the size of that buffer as an additional argument. That will enable them to catch overly long input and prevent writing past the buffer.


我认为您不能使用插入运算符(>>)来读取数组.您应该使用 read() [ getline() [
I don''t think you can use the insertion operator (>>) to read into an array. You should use read()[^] or getline()[^].

As to your second point why use brackets in the first place? If you do not include a filename then argc will have the value 2, to indicate that argv[2] does not exist.