【问题标题】:Trouble with converting string to lowercase/counting words in C [closed]在C中将字符串转换为小写/计数单词的问题[关闭]
【发布时间】:2013-04-06 21:48:25
【问题描述】:

在我的第三个函数中,我在 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()
{
}

【问题讨论】:

  • 我认为任何人都不应该使用gets。 :-(

标签: c char constants tolower


【解决方案1】:

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

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

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

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

【讨论】:

  • 对不起,我只是按照教授给我的示例代码。那么使用这个会更好吗? scanf("%s", s);我必须把它搬到别的地方吗?抱歉,我显然是新人。
【解决方案2】:

你在变量声明块的开头做。对于旧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

【讨论】:

  • 实际上是在我上次发帖几分钟后收到的,但非常感谢您的帮助。
猜你喜欢
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多