2013-11-14 65 views
-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結合在一起?誰能幫忙?

UPDATE:

我已經改變了我的代碼如下:

#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(); 
} 

問題的結果。我不斷收到負載零

enter image description here

+2

搞笑的是你寫的C代碼的一個組成部分,在C++爲其他。 – devnull

+0

確實如此:D – Joze

+0

*從一個人複製C代碼,從另一個人複製C++代碼? – benjymous

回答

0

的要留在,相應延長while循環:

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

int main() 
{ 
    char string[100], *space; 
    int numSpaces = 0; 

    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; 

    // Replacement and counting are done within the following loop IN ONE GO! 
    while (*space) 
    { 
     if(*space == ' ') 
     { 
      *space = '-'; 
      ++numSpaces; 
     } 
     ++space; 
    } 
    printf("%s\n", string); 
    printf("Replaced %d space characters\n", numSpaces); 

    getchar(); 
} 
+0

添加了下面的結果。繼續獲得大量的零 – AbarthGT

+0

numSpaces是一個int。 %f是int的錯誤格式說明符。 –

+0

printf(「%d \ n」,numSpaces);並沒有解決它 – AbarthGT

1

您可以使用成員函數代替類的std ::的字符串中環或你可以使用標準算法替換應用於你的字符串。至於我,我會選擇標準的alforithm。

例如

std::replace(input.begin(), input.end(), ' ', '-'); 
+0

至於計數器,然後再次可以使用標準算法std :: count,前提是您使用C++編寫程序。 –

0

要繼續與第一個片段的精神:

int replaced = 0; 
while (*space == ' '? (replaced++, *space++ = '-'): *space++);