在C中将字符串转换为小写/计数单词时出现问题

时间:2013-04-14 20:31:44

标签: c char const tolower

在我的第三个函数中,我在const char * it = s时遇到语法错误;当我尝试编译。我的朋友得到了这个程序来处理他的编译器,但我使用的是Visual Studio,它不会编译。任何和所有的帮助将非常感谢!

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


//Declaring program functions
char concStrings(); 
int compStrings();
int lowerCase();
int birthday();

//Main function begins the program execution
int main (void)
{
concStrings( );
compStrings();
lowerCase();
birthday();

}
//end main function

//concatenate function
char concStrings ( )
{
char string1[20];
char string2[20];
char string3[50] = "";;

printf("Enter in two strings:");
gets(string1);
gets(string2);

strcat(string3, string1);
strcat(string3, "-");
strcat(string3, string2);

printf("The new string is: %s\n", string3);

}

// compare function
int compStrings() 
{
char string1[20];
char string2[20];
int result;

printf ( "Enter two strings: ");
//  scanf( "%s%s", string1, string2 );
gets(string1);
gets(string2);

result = strcmp ( string1, string2 );

if (result>0)
printf ("\"%s\"is greater than \"%s\"\n", string1, string2 );
else if (result == 0 )
printf ( "\"%s\" is equal to \"%s\"\n", string1, string2 );
else
printf ( "\"%s\" is less than \"%s\"\n", string1, string2);
return 0;
}

//lowercase function
int lowerCase()
{
char s[300];
int x;
int counted = 0;
int inword = 0;

printf ("Enter a sentence:");
//  scanf("%s", s);
gets(s);

const char* it = s;

printf ("\nThe line in lowercase is:\n");

for (x = 0; s[x] !='\0'; x++)
printf ("%c", tolower(s[x]));

do
{ 
switch(*it) 
{ 
  case '\0': case ' ': case '\t': case '\n': case '\r':
    if (inword)
   {
     inword = 0; counted++;
    }
    break; 
  default: 
    inword = 1;
 } 
 }
while(*it++);

printf("\nThere are %i words in that sentence.\n", counted);

return 0;
}

int birthday()
{
}

2 个答案:

答案 0 :(得分:1)

C89(MSVC遵循C89标准)禁止在块中混合使用声明和语句:

gets(s);
const char* it = s;

it对象的声明是在gets函数调用之后,C89不允许这样做。

此外,gets功能已在最新的C标准中删除,应在所有C程序中不惜一切代价避免使用。

答案 1 :(得分:0)

你在变量声明块的开头做。对于旧c。

更改为

int lowerCase()
{
char s[300];
int x;
int counted = 0;
int inword = 0;
const char* it;

printf ("Enter a sentence:");
//  scanf("%s", s);
gets(s);

it = s;

rename progname.c progname.cpp