我创建了一个从文本文件中读取并删除特殊字符的程序。我似乎不能编写更好的if语句。请帮帮忙。我在网上搜索了正确的代码语句,但它们都有高级代码语句。我正在学习的这本书有最后(第14章)关于字符串和文件打开和关闭代码的章节。我尝试创建一个特殊字符数组,但不起作用。请帮帮我!
int main()
{
string paragraph = "";
string curChar = "";
string fileName = "";
int subscript=0;
int numWords=0;
ifstream inFile; //declaring the file variables in the implement
ofstream outFile;
cout << "Please enter the input file name(C:\owner\Desktop\para.txt): " << endl;
cin >> fileName;
inFile.open(fileName, ios::in); //opening the user entered file
//if statement for not finding the file
if(inFile.fail())
{
cout<<"error opening the file.";
}
else
{
getline(inFile,paragraph);
cout<<paragraph<<endl<<endl;
}
numWords=paragraph.length();
while (subscript < numWords)
{
curChar = paragraph.substr(subscript, 1);
if(curChar==","||curChar=="."||curChar==")"
||curChar=="("||curChar==";"||curChar==":"||curChar=="-"
||curChar=="\""||curChar=="&"||curChar=="?"||
curChar=="%"||curChar=="$"||curChar=="!"||curChar==" ["||curChar=="]"||
curChar=="{"||curChar=="}"||curChar=="_"||curChar==" <"||curChar==">"
||curChar=="/"||curChar=="#"||curChar=="*"||curChar=="_"||curChar=="+"
||curChar=="=")
{
paragraph.erase(subscript, 1);
numWords-=1;
}
else
subscript+=1;
}
cout<<paragraph<<endl;
inFile.close();
发布于 2010-12-03 16:25:15
您可能需要查看strchr
函数,该函数在字符串中搜索给定的字符:
include <string.h>
char *strchr (const char *s, int c);
strchr函数返回一个指向所定位字符的指针,如果该字符未出现在字符串中,则返回一个空指针。
类似于:
if (strchr (",.();:-\"&?%$![]{}_<>/#*_+=", curChar) != NULL) ...
您必须将curChar
声明为char
而不是string
,并使用:
curChar = paragraph[subscript];
而不是:
curChar = paragraph.substr(subscript, 1);
但它们是相对较小的更改,而且,由于您声明的目标是I want to change the if statement into [something] more meaningful and simple
,我认为您会发现这是实现它的一个非常好的方法。
发布于 2010-12-03 16:29:28
在<cctype>
头中,我们有像isalnum(c)
这样的函数,当c是字母数字字符时,它返回true,isdigit(c)
等。我想你要找的条件是
if(isgraph(c) && !isalnum(c))
但是c必须是char
,而不是std::string
(从技术上讲,c必须是int
,但转换是隐式的:) hth
附注:这不是最好的主意,但是如果你想在curChar
中继续使用std::string
,c将是这个char c = curChar[0]
发布于 2010-12-03 16:38:34
既然您正在学习c++,我将向您介绍擦除的c++迭代器方法。
for (string::iterator it = paragraph.begin();
it != paragraph.end();
++it)
while (it != paragraph.end() && (*it == ',' || *it == '.' || ....... ))
it = paragraph.erase(it);
首先,尝试使用iterator
。这不会给你带来最好的性能,但它的概念将帮助你使用其他c++结构。
if(curChar==","||curChar=="."||curChar==")" ......
其次,单引号'
和双引号"
不同。您可以对char
使用'
。
https://stackoverflow.com/questions/4343643
复制相似问题