运行程序后没有输出

No output after running the program

本文关键字:输出 程序 运行      更新时间:2023-10-16

简而言之,我是 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
    {}

所以调试这个。

看看如果你输入一个单词,其中的字母是偶数个字母,末尾有空格,就像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;
}

你的解决方案(算法)是完全错误的!首先,您应该用空格分隔每个单词,

if(strchr(s,'')) 

然后你应该找到分隔词的长度,然后将其替换为#。