c++ - 字符串管理 C/C++ & 读写 txt 文件

标签 c++ string

我在分别从文件读取字符串和向文件写入字符串时遇到问题。

目的: 要将字符串作为完整的句子输入文本文件,请从文本文件中读取字符串并使用函数将所有以元音字母开头的单词分开并将它们显示为句子。 (句子只需要由字符串中以元音开头的单词组成。)

问题: 代码按预期工作,但当我从 txt 文件中提取子字符串时,我使用 getline() 函数从 txt 文件中获取字符串,它包括元音后的整个文件,而不仅仅是单词。我无法理解如何使子字符串只包含单词。

代码:

#include <fstream>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
string vowels(string a)
{
    int c=sizeof(a);
    string b[c];
    string d;
    static int n;
    for(int i=1;i<=c;i++)
    {
    if (a.find("a")!=-1)
    {
        b[i]=a.substr(a.find("a",n));
        d+=b[i];
        n=a.find("a")+1;
    }
    else if (a.find("e")!=-1)
    {
        b[i]=a.substr(a.find("e",n));
        d+=b[i];
        n=a.find("e")+1;
    }
    else if (a.find("i")!=-1)
    {
        b[i]=a.substr(a.find("i",n));
        d+=b[i];    
        n=a.find("i")+1;
    }
    else if (a.find("o")!=-1)
    {
        b[i]=a.substr(a.find("o",n));
        d+=b[i];
        n=a.find("o")+1;
    }
    else if (a.find("u")!=-1)
    {
        b[i]=a.substr(a.find("u",n));
        d+=b[i];
        n=a.find("u")+1;
    }
    }
    return d;
}
int main()
{
    string input,lne,e; 
    ofstream file("output.txt", ios::app);
    cout<<"Please input text for text file input: ";
    getline(cin,input);
    file << input;
    file.close();
    ifstream myfile("output.txt");
    getline(myfile,lne);
    e=vowels(lne);
    cout<<endl<<"Text inside file reads: ";
    cout<<lne;
    cout<<endl;
    cout<<e<<endl;
    system("pause");
    myfile.close();
    return 0;
}

最佳答案

我没有非常仔细地阅读您的代码,但有几点很突出:

  1. 查找 find_first_of - 它会大大简化您的代码。
  2. sizeof(a) 当然不会像您认为的那样做 [除非您认为它给您 std::string 类类型的大小 - 这让它作为一个用例变得相当奇怪,为什么不使用 12 或 24?]
  3. find(和 find_first_of),从技术上讲,当函数没有找到您想要的内容时,不会返回 -1。它返回 std::string::npos [可能看起来是 -1,但 a) 不保证是,b) 未签名所以不能为负]。
  4. 你的程序只读一行。
  5. x.substr(n) 将从位置 n 开始为您提供 x 的字符串 - 这就是您想要的吗?
  6. 不要重复find,使用p = x.find("X"); 然后执行x.substr(p) [假设这就是你想要的]。

关于c++ - 字符串管理 C/C++ & 读写 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30861268/

相关文章:

java - 将大写字符与小写字符匹配,Java

c++ - 在这种情况下是否有必要进行范围解析?

c++ - 如何禁用 Windows 上的调试断言对话框?

c++ - WM_PAINT Bitblitting 多次?

string - 在 Swift 3 中将数据转换为字符串

string - 字符串中 2 个字符之间的汇编切换

C++ 按值返回集合

c++ - forward<T>(a) 和 (T&&)(a) 有什么区别

Python 统一码编码错误 : 'ascii' codec can't encode character in position 0: ordinal not in range(128)

string - 如何删除两个字符串之间的冗余匹配?