我在通过printf将字符串作为整数返回时遇到问题。这是我一直得到的错误,但是如果我只看到%i到%s,它就会编译和打印文本。我需要在字符串中打印字母数,而不是实际文本本身。
readability.c:20:20: error: format指定类型'int‘,但是参数有类型'string’(又名'char *') -Werror,-Wformat printf("%i\n",文本);~~ ^~~ %s
我的count_letters函数似乎工作正常,但我肯定我有一个错误,我错过了。这里的代码:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int count_letters(string text);
int main(void)
{
// provides text: statement
printf("Text:");
// gets string from user
string text = get_string(" ");
// should count amount of letters and skip spaces and punctutation
int count_letters(string text);
// prints number of characters in int form
printf("%i\n", text);
}
int count_letters(string text)
{
int letters = 0;
int i;
for (i = 0; letters < strlen(text); i++)
{
if isalpha(text[i])
{
letters++;
}
}
return letters;
}发布于 2022-04-06 21:56:22
我不知道cs50头是从哪里来的,但我认为它来自于一个过程。我看到了两个问题:
int count_letters(string text); in main:在此:
// should count amount of letters and skip spaces and punctutation
int count_letters(string text);您可以重新声明函数,而不是使用它和获取它的返回值,而是使用类似于int result=count_letters(text);的东西。
在此:
// prints number of characters in int form
printf("%i\n", text);如果传递的是一个字符串(类型char*),但是%i (或%d)需要一个整数,您可以(而且应该)使用前面函数的返回值(在本例中是:如果您进行了我在1中建议的修改,则类似于text )。
否则,在标准c中(请记住,我保持了它的简单性,并试图执行类似于您的代码的操作,因此缺少错误检查):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int count_letters(char* text);
int main(void)
{
// provides text: statement
printf("Text:");
// gets string from user with size 14 (+1 for \0)
char text[15];
scanf("%14s", text);
// should count amount of letters and skip spaces and punctutation
int result=count_letters(text);
// prints number of characters in int form
printf("%i\n", result);
}
int count_letters(char* text)
{
int letters = 0;
int i;
for (i = 0; letters < strlen(text); i++)
{
if isalpha(text[i])
{
letters++;
}
}
return letters;
}https://stackoverflow.com/questions/71759314
复制相似问题