程序提示用户输入一个短语,然后根据单词创建一个首字母缩略词。与有大写字母的传统缩略词不同,字母的大小写保持不变。如果我进入市政厅是旧的,我应该得到TTHio。如何使用isspace来确保我的程序正常运行,因为如果相邻有多个空格,它不会组合字符?它也不能处理标签。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string create_acronym(string str);
int main()
{
cout << "This program tests the acronym function." << "\n";
while (true)
{
cout << "\nPlease enter a string: ";
string str;
getline(cin, str);
if (str == "")
{
break;
}
cout << "\n\nThe acronym is \"" << create_acronym(str) << "\"" << "\n";
}
return 0;
}
string create_acronym(string str)
{
string acronym = "";
acronym = str.at(0);
for (int i = 0; i < str.length(); i++)
{
if (str.at(i) == ' ')
{
acronym += str.at(i+1);
}
}
return acronym;
}发布于 2015-08-27 03:40:22
请记住,您需要输出下一个非空间:
string create_acronym( const string & str )
{
string acronym;
bool use_next = true;
for ( char c : str )
{
bool space = isspace(c);
if ( use_next && !space ) acronym += c;
use_next = space;
}
return acronym;
}https://stackoverflow.com/questions/32240254
复制相似问题