【问题标题】:How do I create a string consisting of characters read from a text file?如何创建由从文本文件中读取的字符组成的字符串?
【发布时间】:2013-10-06 09:20:48
【问题描述】:

我正在尝试读取代码并对其进行格式化,以便它在某个点之后切断并进入新行。起初,我试图简单地继续显示连续的字符,并在此时读取的字符数量超过限制后使其进入换行符。但是,如果一个词 超出限制,我需要让该词开始新行。由于我完全不知道如何仅使用字符来做到这一点,因此我决定尝试使用字符串数组。我的代码如下

char ch;
string words[999];
//I use 999 because I can not be sure how large the text file will be, but I doubt it   would be over 999 words
string wordscount[999];
//again, 999. wordscount will store how many characters are in the word
int wordnum = 0;
int currentnum = 0;
//this will be used later
while (documentIn.get(ch))
{
if (ch != ' ')
//this makes sure that the character being read isn't a space, as spaces are how we differentiate words from each other
{
cout << ch;
//this displays the character being read

在我的代码中,我想将所有字符“保存”到一个字符串中,直到该字符为空格。我不知道该怎么做。有谁可以帮我离开这里吗?我想它会是这样的;

words[wordnum] = 'however i add up the characters'
//assuming I would use a type of loop to keep adding characters until I reach a 
//space, I would also be using the ++currentnum command to keep track of how
//many characters are in the word
wordscount[wordnum] = currentnum;
++wordnum;

【问题讨论】:

  • 实现 iostream 提取操作符在拉取std::string 时跳过空格,但使用它来分隔,这可以在几行代码中完成。
  • 我真的不知道那是什么意思,但我查了一下分隔符,我想我现在明白了吗?我知道我可以将空格分隔符声明为std::string delimiter = " ";,但是,我不知道如何让它为整个程序做到这一点的语法。我想做某种循环,如下所示; '分割第一个单词的语法'; '第一个单词' = words[wordnum]; '计算单词中字符的数量' = wordscount[wordnum];字数++;我会以正确的方式去做吗?我该如何做语法?

标签: c++ string char


【解决方案1】:

使用输入文件流循环遍历将它们添加到向量中的单词,然后 vector.size() 将是单词计数。

std::ifstream ifs("myfile.txt");

std::vector<std::string> words;
std::string word;
while (ifs >> word)
   words.push_back(word);

默认情况下会跳过空白,while 循环将继续执行,直到到达文件末尾。

【讨论】:

  • 以下代码不起作用。该文件不是通过“myfile.txt”之类的东西打开的,它是通过命令行参数给出的。代码char ch; while (documentIn.get(ch)) {} 是有效的,但我不能只用documentIn 替换ifs。我不完全确定流是如何工作的。
【解决方案2】:

我不知道你真正想做什么。

如果你想从文件中恢复每一行,你可以这样做:

std::ifstream ifs("in");
std::vector<std::string> words;
std::string word;
while (std::getline(ifs, word))
{
    words.push_back(word);
}
ifs.close();

函数 std::getline() 不会省略空格,例如 ' ', '\t' ,而它将通过 ifs >> word 进行删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2016-07-01
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多