从 C++ 字符串中删除元音

removing vowels from c++ string

char arr[5000];
ifstream is("test.txt"); 
is.get(arr,5000);
int i = 0;
int j = 0;
cout << arr << endl;
char anar[5000];
while (arr[i] != '[=10=]')
{
    if (arr[i] == 'i' || arr[i] == 'a' || arr[i] == 'e' ||
    arr[i] == 'o' || arr[i] == 'u')
        {
        ++i; 
        }
    else anar[j] = arr[i]; ++j; ++i; 
}++j; anar[j] = '[=10=]';
cout << anar << endl; 
ofstream os("test.txt"); 
os.write(anar, sizeof(char)); 
cout << "written successfully" << endl;

应该从文件中读取数据并从该字符串中删除元音。删除元音后,它应该将结果分配给另一个字符串。但是元音字母看起来很奇怪,而且写入的文件只有一个字符长。

你认为sizeof(char)有多大?那么这要写多少个字符呢?

os.write(anar, sizeof(char)); 

你的数组中实际上有 j 个字符,所以这有效

os.write(anar, j); 

但是因为你有一个以空字符结尾的字符数组,更简单的是

os << anar;

还有一些错误,看这个循环

while (arr[i] != '[=13=]')
{
    if (arr[i] == 'i' || arr[i] == 'a' || arr[i] == 'e' ||
    arr[i] == 'o' || arr[i] == 'u')
        {
        ++i; 
        }
    else anar[j] = arr[i]; ++j; ++i; 
}++j; anar[j] = '[=13=]';

您似乎缺少 {} if 语句的 else 部分。由于某种原因,您在 while 循环之后还有一个额外的 ++j 。它应该是这样的(我认为)

while (arr[i] != '[=14=]')
{
    if (arr[i] == 'i' || arr[i] == 'a' || arr[i] == 'e' ||
    arr[i] == 'o' || arr[i] == 'u')
    {
        ++i; 
    }
    else
    {
        anar[j] = arr[i];
        ++j;
        ++i;
    } 
}
anar[j] = '[=14=]';

请注意,如果您养成始终如一地缩进代码的习惯,发现这些问题会容易得多。你应该这样做。

顺便说一句,您的代码中没有 C++ 字符串,只有字符数组。

john 已经给出了很好的答案。这样,问题就解决了。

我想向您推荐学习一点 C++ 和所有现有的库。尤其是C++算法库非常强大

看下面的程序:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>


int main() {

    // Open files and check, if they could be opened
    if (std::ifstream is("withvowels.txt"); is)
        if (std::ofstream os("withoutvowels.txt"); os)

            // Copy file and remove vowels
            std::copy_if(std::istreambuf_iterator<char>(is), {}, std::ostreambuf_iterator<char>(os), [](const char c) { return !((0x208222 >> (c & 0x1f)) & 1); });
}

所以,本质上,我们只有 3 个语句:2 次 if 带有初始化程序。然后一个 copy_if 带有用于元音检测的 lambda。

如果您想了解有关 lambda 和元音检测的更多信息,可以阅读我的其他一篇文章


编辑

op问,如何将文件读入std::string。我添加了一段新代码,首先将完整文件读入 std::string,然后 erase/remove 元音。结果显示在 std::cout

请看:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <string>

int main() {
    // Open file and check, if it could be opened
    if (std::ifstream is("r:\withvowels.txt"); is) {

        // Read the complete file into string variable s
        std::string s(std::istreambuf_iterator<char>(is), {});

        // Remove all vowels from string
        s.erase(std::remove_if(s.begin(), s.end(), [](const char c) { return ((0x208222 >> (c & 0x1f)) & 1); }), s.end());

        // Show result
        std::cout << s;
    }
}