【问题标题】:Manipulation of lines of text文本行的操作
【发布时间】:2013-08-31 14:12:55
【问题描述】:

下面的代码尝试一次处理多行文本。

1.我的第一个问题是编写一个循环来读取多行文本(使用 scanf())并在输入的第一个字符是换行符时退出。这些文本行有一些条件:第一个字符必须是 2 到 6 之间的数字,后跟一个空格和一行文本(

2.我的第二个问题是弄清楚如何根据输入的第一个数字将字母从小写转换为大写,反之亦然。我必须进行这些转换,但我不知道如何调用它们来更改文本。例如:如果我输入“3 apples andbananas”,正确的输出应该是“AppLes And 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])); 
}

【问题讨论】:

  • 不要使用scanf 阅读“行”,而是使用fgets。并使用fgets 的返回值来查看是否应该继续循环(例如while (fgets(...)))。

标签: c string visual-c++


【解决方案1】:

您还可以定义一个函数printNthUpper(),它接受一个字符串和一个整数n,指定哪些字符以大写形式打印。该函数将是一个类似于您已经拥有的函数的循环,但有一个条件,比较提供的整数值和给定字母的索引以决定是否 调用 toupper()(例如printf("%c", i%n == 0 ? toupper(s[i]) : s[i]);)。

【讨论】:

    【解决方案2】:

    要编写一个循环来读取多行文本,您可以将基于条件的无限循环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)  
    
    { 
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多