C++ 简介 : self study

标签 c++

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

相关文章:

c++ - OpenGL:着色/插值不工作

c++ - C++中的对象序列化

c++ - 在文件中维护链表

c++ - 将字符串转换为 time_t,然后将 time_t 转换回字符串

c++ - QMessageLogContext 的字段(如 : file, 函数、行)为空或为零

c++ - 是否可以强制 `std::make_shared` 使用类的新运算符?

c++ - gmock : Returns distinct values on each mock invocation

c++ - 好问(不是编译时强制)子类创建者做某些事情?

c++ - 如何将 OpenGL 数学 (GLM) 添加到 Xcode 4?

c++ - 这些叫什么