sách gpt4 ai đã đi

c++ - istream 运算符跳过空格字符

In lại 作者:行者123 更新时间:2023-11-30 04:41:36 28 4
mua khóa gpt4 Nike

void transferData(ifstream& input_file, ofstream& output_file)
{
char ch;
while (input_file >> ch) {
if ((ch >= 97 && ch <= 118) || (ch >= 65 && ch <= 86)) {
ch += 4;
output_file << ch;
}
else if ((ch >= 87 && ch <= 90) || ch >= 119 && ch <= 122) {
ch -= 22;
output_file << ch;
}
else if (ch == 32) {
output_file << '\t';
}
khác
output_file << ch;

}
}

该代码有效,但它不会在输出文件中的单词之间添加空格。这是什么原因?

Input: "This text is to test the program."
Output: "Xlmwxibxmwxsxiwxxlitvskveq."

1 Câu trả lời

Việc sử dụng của bạn std::noskipws.

while (input_file >> std::noskipws >> ch)

默认情况下,流在读入变量之前会跳过空白。这在某种程度上是 C scanf() 函数的后遗症(它在读入变量之前跳过空白)。

注意:这是运算符>>的一个属性。

您还可以使用迭代器来完成这项工作:

std::istreambuf_iterator loop(input_file);
std::istreambuf_iterator end;

for(;loop != end; ++loop) {
ch = *loop;
// STUFF
}

如果您有 C++20,我们可以使用基于范围的循环使它看起来更好:

// Note I don't have a C++20 compiler so sort of guessing based on API.
for(char ch: std::ranges::range(std::istreambuf_iterator loop(input_file), std::istreambuf_iterator{}) {
// STUFF
}

关于c++ - istream 运算符跳过空格字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096026/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com