我的代码中strncpy中的编译错误,用于查找和打印最长的单词

时间:2015-12-01 20:51:16

标签: c arrays string function strncpy

我写了一个程序来找到最长的单词并打印出来。

我的代码是:

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

int MaxWord(char text[],char[]);

int main (void){
  char text[1000];
  char word[1000];
  int max;

  printf("geben Sie den Text bitte : ");
  gets(text);
  max=MaxWord(text,word);
  printf("ist mit %d Zeichen das laengste wort im Text\n\n\n",max);
  return 0;
}
int MaxWord(char text[], char word[])
{
  char i;
  int ctr=0;
  int max=0;
  int len;
  char begin=0;

  len=strlen(text);
  for(i=0;i<len+1;i++)
  {
    if(isalpha(text[i]))
    {
        if(ctr==0)
        {
            begin=i;
        }
        ctr++;
    }
    else 
    {

        if(ctr>max)
        {
            max=ctr;

        }

        ctr=0;
    }
 }
 strncpy(word,begin,max);
 printf("%s ",word);
 return max;
}   

,错误是:

  

错误#2140:在参数2中输入'strncpy'错误;预期'const char * restrict'但找到'char'。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

首先,您不应该使用gets()函数。请改用scanf。 另见 http://www.cplusplus.com/reference/cstring/strncpy/

函数strncpy需要一个const char *(这样你就可以确保函数不会修改源字符串)并且你传递一个char。因此错误。请修改您的函数以传入char指针。

您需要通过传入正确的源字符串来重新检查逻辑并修复strncpy调用。

答案 1 :(得分:1)

MaxWord中的逻辑存在缺陷:您总是尝试复制遇到的最长字的最后一个字。 char类型不适合ibegin,因为text中的偏移量可能大于127

此外,strncpy没有按照您的想法执行,它是一个容易出错的函数,可能无法终止目标缓冲区。不要使用此功能。

不要使用gets,因为它无法安全使用,无效输入会导致缓冲区溢出。

以下是更正后的版本:

int MaxWord(const char *text, char *word) {
    int i, ctr = 0, max = 0, len, begin = 0, best = 0;

    len = strlen(text);
    for (i = 0; i < len; i++) {
        if (isalpha((unsigned char)text[i])) {
            if (ctr == 0) {
                begin = i;
            }
            ctr++;
        } else {
            if (ctr > max) {
                best = begin;
                max = ctr;
            }
            ctr = 0;
        }
    }
    memcpy(word, test + best, max);
    word[max] = '\0';
    printf("%s ", word);
    return max;
} 

text[i]强制转换为(unsigned char)似乎令人惊讶,但isalpha()被定义为使用int的值unsigned charEOF常量-1(通常定义为char)。如果您的编译器认为text是有符号类型,则isalpha中设置为高位的字符将被视为否定,并且在传递给laengste时可能会被符号扩展,从而可能会调用错误或未定义的行为

您的代码的另一个问题是确定字边界:如果您längste正确键入isalpha()ä可能会错误地考虑编码(venv)dyn-160-39-161-214:proj Bren$ python manage.py Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module> class Permission(models.Model): File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__ new_class.add_to_class('_meta', Options(meta, **kwargs)) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class value.contribute_to_class(cls, name) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 241, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/utils.py", line 112, in load_backend return import_module('%s.base' % backend_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Bren/Desktop/fss/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb 的字符或字符}作为分隔符而不是字母。欢迎来到错综复杂的角色编码世界!