C ++将字符串的一个字符存储到char变量中

时间:2013-10-29 15:56:17

标签: c++ string char

我正在尝试获取字符串的最后一个“char”并将其存储为char,以便我可以对其执行bool功能。例如,如果我传入“Hello,world”,我的代码将找到','并将其存储为字符串结尾。我想将','转换为char并运行检查。 ','将只是最后一个“char”。

我的代码如下:

int main() {
string str, str2, pigsentence, finalsentence, orgstr, end;
int counter, length;
char lchar;
counter = 1;
cout << "Enter a string: ";
getline (cin, str);
cout << endl;

orgstr = str;

//Add in option to move special chars
string::size_type space;
    do {
        space = str.find(' ', 0); //Finds the space(s)
        str2 = str.substr(0, space); //Finds the word
            if(space != string::npos){
                length = str.length();
                end = str.substr(length, 1); //Stores special char as end
                lchar = end;
                    if(specialChar(lchar) != 0) {
                                str.erase(length, 1); //Erases special car
                    }
            str2 = str.substr(0, space); //Finds the word
            cout << "str 2 = " << str2 << endl;
            str.erase(0, space); //Erases the word plus the space
            pigsentence = pigLatinString(str2); //converst the word
            finalsentence = finalsentence + " " + pigsentence + end; //Adds converted word to final string
            cout << "final = " << finalsentence << endl;
            system("pause");
        }else {
            cout << "In the else " << endl;
            length = str.length();
            cout << length << endl;
            str2 = str.substr(0, length); //Finds the word
                for (int i = 0; i < str.length(); i++ ) { 
                    if (specialChar(str[i])) {
                        end = str.substr(i, 1); //Stores special char as end
                        str.erase(i, 1); //Erases special car


                } 
                    }
                str2 = str.substr(0, length); //Finds the word
                str.erase(0, length); //Erases the word
                pigsentence = pigLatinString(str2); //converst the word
                finalsentence = finalsentence + " " + pigsentence + end; //Adds converted word to final string
                counter = 0;
            }
        }while(counter != 0); //Loops until counter == 0

    cout << "The pig Laten form of " << orgstr << " is: " << finalsentence << endl;

    return 0;
}

bool功能

bool specialChar(char ch) {
switch(ch) {
case ',':
case ':':
case ';':
case '.':
case '?':
case '!':
    return true;
default:
        return false;
    }
}

有没有办法接受字符串并对其进行检查?我尝试使用字符串和bool,但它给了我标志。

0 个答案:

没有答案