首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >文本行的操作

文本行的操作
EN

Stack Overflow用户
提问于 2013-08-31 22:12:56
回答 2查看 81关注 0票数 0

下面的代码试图一次操作几行文本。

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

2.我的第二个问题是弄清楚如何根据输入的第一个数字将字母从小写转换为大写,反之亦然。我必须使用函数来进行这些转换,但我不知道如何调用它们来更改示例:如果我输入"3个苹果和香蕉“,正确的输出应该是"AppLes text.For BanNas”,您会看到,空格被忽略,文本始终以大写字母开头。

代码语言:javascript
复制
#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])); 
}
EN

回答 2

Stack Overflow用户

发布于 2013-08-31 22:49:47

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

票数 0
EN

Stack Overflow用户

发布于 2013-08-31 22:58:33

要编写读取多行文本的循环,可以将基于条件的无限循环fgets结合使用,而不是使用scanf。

代码语言:javascript
复制
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)  

{ 

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18549067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档