gpt4 book ai didi

c++ - 从 C++ 中的文本文件中打印出空格

转载 作者:行者123 更新时间:2023-11-30 02:51:40 25 4
gpt4 key购买 nike

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <stdio.h>
using namespace std;

int main()
{
ifstream file;
string filename;
char character;
int letters[153] = {};

cout << "Enter text file name: ";
cin >> filename;
file.open(filename.c_str());
if (! file.is_open())
{
cout << "Error opening file. Check file name. Exiting program." << endl;
exit(0);
}

while (file.peek() != EOF)
{
file >> character;
if(!file.fail())
{
letters[static_cast<int>(character)]++;
}
}

for (int i = 0; i <= 153; i++)
{
if (letters[i] > 0)
{
cout << static_cast<char>(i) << " " << letters[i] << endl;
}
}

exit(0);
}

#endif

大家好,我当前的代码计算文本文件中每个字母的出现频率。但是,它不计算空格的数量。有没有一种简单的方法可以打印出 .txt 文件中的空格数?

另外,当我试图访问一个 vector 项时,为什么会遇到段错误?例如,如果我使用:

cout << ""+ letters[i] << endl;, 它显示一个段错误。有什么想法吗?

非常感谢。

最佳答案

默认情况下,iostreams 格式化输入提取操作(使用 >>> 的操作)会跳过所有空白字符以到达第一个非空白字符。也许令人惊讶的是,这包括 char 的提取运算符。为了将空白字符视为要照常处理的字符,您应该更改使用 noskipws manipulator处理前:

file << std::noskipws;

不要忘记稍后重新设置:

file << std::skipws;

如果您是那些疯狂的人中的一员,想要制作一个函数来保留流状态的这一方面(或什至所有方面)在它退出之前,该怎么办?当然,C++ 提供了一种令人沮丧的丑陋方式来实现这一点:

std::ios_base::fmtflags old_fmt = file.flags();
file << std::noskipws;

... // Do your thang

file.flags(old_fmt);

关于c++ - 从 C++ 中的文本文件中打印出空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com