更新时间:2022-02-24 22:43:27
您可能对逻辑有很多误解.如果您希望能够从作为第一个参数给出的文件名中进行读取,或者如果没有给出任何参数,则可以从stdin
中进行读取,则可以创建一个函数,该函数从输入流中读取string
并仅输出所有以a分隔的单词通过将istream
引用传递给函数并传递打开的ifstream
或std::cin
来分隔空格(专门处理第一个单词).
You may be overthinking the logic quite a bit. If you want to be able to read from the filename given as the first argument or from stdin
if no argument is given, you can create a function that reads a string
from the input stream and simply outputs all words separated by a space (handling the first word specially) by passing an istream
reference to the function and either passing the open ifstream
or std::cin
.
一个简短的示例可能如下所示:
A short example could be something like the following:
#include <iostream>
#include <fstream>
#include <string>
void squishws (std::istream& in)
{
bool first = true;
std::string str;
while (in >> str) /* while words read */
if (first) { /* no space before 1st word */
std::cout << str;
first = false;
}
else /* output remaining words with 1 space */
std::cout << " " << str;
std::cout << "\n"; /* tidy up with newline */
}
int main (int argc, char **argv) {
if (argc > 1) { /* read from file if given as argument */
std::ifstream f (argv[1]);
if (f.is_open())
squishws (f);
else {
std::cerr << "error: file open failed.\n";
return 1;
}
}
else { /* read from stdin */
squishws (std::cin);
}
return 0;
}
您可以根据需要添加输出文件引用,也可以直接在命令行上将输出重定向到输出文件.
You can add an output file reference, as required, or simply redirect the output to an output file on the command line.
示例输入文件
$ cat dat/wswords.txt
this is a
file with
multiple
whitespace.
使用/输出示例
$ ./bin/file_rmwhitespace < dat/wswords.txt
this is a file with multiple whitespace.