2013-08-31 47 views
0

下面的代碼嘗試在當時處理多行文本。操作文本行

1.我的第一個問題是編寫一個循環來讀取幾行文本(使用scanf()),並在輸入的第一個字符是換行符時退出。這些文本行具有一些條件:第一個字符必須是2到6之間的數字,後跟一個空格和一行文本(< 80)。該數字將使文本「跳舞」。

2.第二個問題是如何根據輸入的第一個數字來確定如何將字母從小寫轉換爲大寫字母和反之。例如:如果我輸入「3蘋果和香蕉」,正確的輸出應該是「AppLes和BanNas」。如你所見,白色空間被忽略,文本始終以大寫字母開頭。

#include <stdio.h> 
#include <stdlib.h> 
#include <string> 
#include <ctype.h> 

using namespace std; 
void print_upper(string s1); 
void print_lower(string s2); 
void main(void) 
{ 
    char text[80]; 
    text[0]='A';//Initialization 
    int count_rhythm; 

    while (text[0] != '\n'){//To make the loop run until a newline is typed 
     scanf(" %79[^\n]",text); 
     if(isdigit(text[0])) //To verify that the first character is a number 
     { 
      printf("\nGood");//Only to test 
     } 
     else 
     { 
      printf("\nWrong text\n");//Only to test 
     } 
    } 
} 

void print_upper(string s1)//Print capital letters 
{ 
    int k1; 
    for(k1=0; s1[k1]!='\0'; ++k1) 
     putchar(toupper(s1[k1])); 
} 

void print_lower(string s2)//Print small letters 
{ 
    int k2; 
    for(k2=0; s2[k2]='\0'; ++k2) 
     putchar(tolower(s2[k2])); 
} 
+1

不要使用'scanf'讀取「行」,而應使用'fgets'。並使用'fgets'的返回值來查看是否應該繼續循環(例如'while(fgets(...))')。 –

回答

0

你也可以定義一個函數printNthUpper()這將需要一個字符串和整數n,將使用大寫字母指定要打印的字符。該函數的功能與您已有的函數類似,但有條件將提供的整數值與給定字母的索引進行比較,以決定是否 調用toupper()(例如printf("%c", i%n == 0 ? toupper(s[i]) : s[i]);)。

0

寫一個循環來讀幾行文字,你可以結合使用基於狀態的無限循環與fgets,而不是使用scanf函數。

char line[80]; 
char result[80] 

while(1) 
{ 
    fgets(line,sizeof(line),stdin); //read line with fgets 
    puts(line); 

    if(line[0]=='\n') 
     break; 

    if((strlen(line)>=4) &&'2'< =line[0] && line[0] <= '6' && line[1]==' ') 
    { 
     strcpy(result,change_case_of_nth_char(line));// call change case of nth letter 
    } 
    else 
    { 
     //prompt user to enter input again 
    } 

} 

char *change_case_of_nth_char(char *str) 

{ 

}