-3

スペースをダッシュ​​に置き換えるプログラムがあります。ここで、置き換えられたスペースの量を数えて印刷できるようにする必要があります。これがスペーシング置換のコーディングです。

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main()
{
    char string[100], *space;
    {
    printf("Enter a string here: \n"); //Enter a string in command prompt
    fgets(string, sizeof(string), stdin); //scans it and places it into a string
    space = string;

    while (*space == ' '? (*space = '-'): *space++);
    printf("%s\n", string);
    }
    getchar();
}

これは、スペースの数をカウントするコードです。

#include <iostream>
#include <string>

int count( const std::string& input )
{
    int iSpaces = 0;

    for (int i = 0; i < input.size(); ++i)
        if (input[i] == ' ') ++iSpaces;

    return iSpaces;
}

int main()
{
    std::string input;

    std::cout << "Enter text: ";
    std::getline( std::cin, input );

    int numSpaces = count( input );

    std::cout << "Number of spaces: " << numSpaces << std::endl;
    std::cin.ignore();

    return 0;
}

2つを組み合わせる方法がわかりませんか?誰でも助けることができますか?

アップデート:

コードを次のように変更しました。

#include <stdio.h>
#include <conio.h>
#include <string.h>

int numSpaces = 0;

int main()
{
    char string[100], *space;
    {
    printf("Enter a string here: \n"); //Enter a string in command prompt
    fgets(string, sizeof(string), stdin); //scans it and places it into a string
    space = string;

    while (*space == ' '? (*space = '-'): *space++);

    printf("%s\n", string);

    }
    while (*space)
{
   if( *space == ' ')
   { 
      *space = '-';
      ++numSpaces;
   }
   ++space;

   printf("%f\n", numSpaces);
}

    getchar();
}

結果に問題あり。私はたくさんのゼロを取得し続けます

ここに画像の説明を入力

4

3 に答える 3

0

最初のスニペットの精神を維持するには:

int replaced = 0;
while (*space == ' '? (replaced++, *space++ = '-'): *space++);
于 2013-11-14T17:44:12.017 に答える