[英]No output after running the program
为了简短起见,我是c ++的初学者,我正在学习字符序列。
这是我的问题:我试图将每个带有偶数个字母的单词改成符号(#),但是我认为我以一种不好的方式解决了这个问题。 运行它时我什么也没得到。
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s[101];
cin.getline(s,101);
int i;
for(int i=0; i<strlen(s); i++)
{
if(strchr(s,' ')) // searching for a space
{}
else
if((strlen(s)%2==0)) //trying to find if the word has an even number
{
strcat(s,"#"); // I'm sticking the # character to the word and then deleting everything after #.
strcpy(s+i,s+i+1);
cout<<s;
}
else
cout<<"Doens't exist";
}
return 0;
}
唯一不包含cout的代码流是
if(strchr(s,' ')) // searching for a space
{}
所以调试一下。
您的解决方案(算法)是完全错误的! 首先,您应该按空格分隔每个单词,
if(strchr(s,' '))
那么您应该找到分隔单词的长度,然后将其替换为#。
看看如果您输入一个单词,并以偶数个字母结尾的空格,如abcd
,将会发生什么情况。 您的程序将搜索空间五次,并且每次都不执行任何操作。
这是我想出的算法:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// declare input string and read it
string s;
getline(cin, s);
// declare vector of strings to store words,
// and string tmp to temporarily save word
vector <string> vec;
string tmp = "";
// iterate through each character of input string
for(auto c : s)
{
// if there is space push the word to vector,
// clear tmp string
if (c == ' ')
{
vec.push_back(tmp);
tmp = "";
continue;
}
// add character to temporary string
tmp += c;
}
// push last word to vector
vec.push_back(tmp);
// clear the input string
s = "";
// iterate through each word
for(auto w : vec)
{
// if number of word's characters are odd
// just add the word itself
// otherwise add '#' symbol
(w.size() % 2) ? s += w : s += '#';
s += ' ';
}
// remove last space
s.erase(s.begin() + s.size() - 1, s.begin() + s.size());
cout << s;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.