gpt4 book ai didi

C++ 简介 : self study

转载 作者:太空狗 更新时间:2023-10-29 21:07:50 28 4
gpt4 key购买 nike

我创建了从文本文件中读取并删除特殊字符的程序。我似乎无法更好地编写 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();

最佳答案

您可能想查看 strchr 函数,该函数在字符串中搜索给定字符:

include <string.h>
char *strchr (const char *s, int c);

The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.

The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.

类似于:

if (strchr (",.();:-\"&?%$![]{}_<>/#*_+=", curChar) != NULL) ...

您必须将 curChar 声明为 char 而不是 string 并使用:

curChar = paragraph[subscript];

而不是:

curChar = paragraph.substr(subscript, 1);

但它们是相对较小的更改,并且由于您声明的目标是我想将 if 语句更改为更有意义和更简单的 [something],我认为您会发现这是一个非常好的实现它的方法。

关于C++ 简介 : self study,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4343643/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com