我在分别从文件读取字符串和向文件写入字符串时遇到问题。
目的: 要将字符串作为完整的句子输入文本文件,请从文本文件中读取字符串并使用函数将所有以元音字母开头的单词分开并将它们显示为句子。 (句子只需要由字符串中以元音开头的单词组成。)
问题: 代码按预期工作,但当我从 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;
}
最佳答案
我没有非常仔细地阅读您的代码,但有几点很突出:
- 查找
find_first_of
- 它会大大简化您的代码。 sizeof(a)
当然不会像您认为的那样做 [除非您认为它给您std::string
类类型的大小 - 这让它作为一个用例变得相当奇怪,为什么不使用 12 或 24?]find
(和find_first_of
),从技术上讲,当函数没有找到您想要的内容时,不会返回 -1。它返回std::string::npos
[可能看起来是 -1,但 a) 不保证是,b) 未签名所以不能为负]。- 你的程序只读一行。
x.substr(n)
将从位置n
开始为您提供x
的字符串 - 这就是您想要的吗?- 不要重复
find
,使用p = x.find("X");
然后执行x.substr(p)
[假设这就是你想要的]。
关于c++ - 字符串管理 C/C++ & 读写 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30861268/