我有一个用破折号替换空格的程序。现在我需要能够计算已替换的空格数量并打印出来。这是我对间距替换的编码。
#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;
}
我不确定如何将两者结合在一起?任何人都可以帮忙吗?
更新:
我已将代码更改为以下内容:
#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();
}
结果有问题。我不断收到很多零