我正在制作一个小字处理器,我遇到了一个问题。我正在尝试制作程序,这样当你按下回车键时,程序将完全停止你的输入,然后是一个空格(我稍后会对段落进行整理)。问题是我无法让程序在最后一个字符中搜索标点符号,然后对结果进行分支。编译器给出了以下错误: ISO C ++禁止指针和整数之间的比较。我目前的代码是:
#include <fstream>
#include <string>
#include <iostream>
#include <cstring>
#include <limits>
using namespace std ;
int main()
{
int i = 0;
string text ;
string text2 ;
string title ;
string usertitle ;
string filelocation = "C:/Users/" ;
string user ;
string punctuation = ". : ! ? "
cout << "Input a title for your file: " ;
getline(cin , title) ;
title.insert(title.length() , ".txt" ) ;
cout << "Your title is: " << title << endl ;
cout << endl << "Input the username associated with your computer: " ;
getline(cin , user) ;
filelocation.append( user ) ;
filelocation.append("/Documents/") ;
filelocation.append(title) ;
cout << "Your chosen file name and location is: " << filelocation << endl ;
for ( i = 1 ; i > 0 ; i++ )
{
if (text == "")
{
cout << "There are a few instructions that you need to follow in order to use this system effectively: " << endl ;
cout << "The first being that if you want to use it, you actually have to use a directory that exists. " << endl ;
cout << "The second being that when you want to exit the program you press enter with nothing typed" << endl ;
cout << "The third being NOT TO USE FULL STOPS, THE PROGRAM WILL PUT THEM IN FOR YOU" << endl ;
cout << "Please begin writing: " << endl ;
getline(cin,text) ;
}
if (text!="")
{
text2.append(text) ; //<===HERE IS WHERE I AM HAVING TROUBLE
if ((text.at(text.size() -1 ) != "!" ) && (text.at(text.size() -1 ) != "?") && (text.at(text.size() -1 ) != ":" ))
{
text2.append(". ") ;
getline(cin, text) ;
}
else
{
getline(cin, text) ;
}
if (text == "")
{
cout << "End of session" << endl ; break ;
}
}
}
ofstream writer( filelocation.c_str() ) ;
if(! writer)
{
cout << "Error opening file for output: " << strerror(errno) << endl ;
return -1 ;
}
else
{
writer << text2 << endl ;
writer.close() ;
}
return 0 ;
}
提前感谢您的帮助!
答案 0 :(得分:4)
"!"
是一个字符串,您想要与一个字符进行比较:'!'
。
答案 1 :(得分:1)
您无法比较"!"
和'!'
。
我建议使用rbegin()
来解决最后一个字符:
text2.append(text.begin(), text.end());
switch(*text.rbegin())
{
case '!':
case '?':
case ':': text2.append(". "); break;
}
getline(cin, text);
if(text.empty())
{
cout << "End of session" << endl;
break;
}
答案 2 :(得分:1)
if ((text.at(text.size() -1 ) != "!" ) && (text.at(text.size() -1 ) != "?") && (text.at(text.size() -1 ) != ":" ))
这既低效又不符合你的想法。 text.at(text.size() -1 )
返回最后一个字符。得到你想要的:
char lastChar = text[text.size() - 1]; // or char lastChar = *text.rbegin();
if (!(lastChar == '.' || lastChar == '?' || lastChar == '!')) // note the single quotes
{
text2.append(". ");
}
getline(cin, text);