[英]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] != '\0')
{
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] = '\0';
cout << anar << endl;
ofstream os("test.txt");
os.write(anar, sizeof(char));
cout << "written successfully" << endl;
應該從文件中讀取數據並從該字符串中刪除元音。 刪除元音后,它應該將結果分配給另一個字符串。 但是元音看起來很奇怪,而且 writen 文件只有一個字符長。
你認為sizeof(char)
有多大? 那么這要寫多少個字符呢?
os.write(anar, sizeof(char));
你的數組中實際上有j
字符,所以這行得通
os.write(anar, j);
但是因為你有一個 null 終止字符數組,所以更簡單的是
os << anar;
其他一些錯誤,看看這個循環
while (arr[i] != '\0')
{
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] = '\0';
看起來您在 if 語句的 else 部分缺少{}
。 出於某種原因,在 while 循環之后還有一個額外的++j
。 這是它的外觀(我認為)
while (arr[i] != '\0')
{
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] = '\0';
請注意,如果您養成一致縮進代碼的習慣,那么發現這些問題會變得多么容易。 你應該做這個。
順便說一句,您的代碼中沒有 C++ 字符串,只有字符 arrays。
約翰已經給出了一個很好的答案。 所以,問題就解決了。
我想向您推薦一些關於 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
with initializer。 然后是一個帶有copy_if
的 copy_if 用於元音檢測。
如果您想了解更多關於 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.