CS50 Pset 2:可读性
我在通过printf作为整数返回字符串时遇到问题。这是我一直遇到的错误,但是如果我只是%i到%s,则它会编译并打印文本。我需要在字符串中打印字母的数量,而不是实际的文本本身。
可读性。C:20:20:错误:格式指定类型'int',但该参数具有type'string'(aka'char *')[-werror,-wormat] 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;
}
I'm having issues returning the string as an integer through printf. Heres the error i keep getting, but if I just %i to %s it compiles and prints text. i need to print the number of letters in a string, not the actual text itself.
readability.c:20:20: error: format specifies type 'int' but the argument has type 'string' (aka 'char *') [-Werror,-Wformat]
printf("%i\n", text);
~~ ^~~~
%s
my count_letters function seems to work okay but I'm sure I have a mistake somewhere that I'm missing. code here:
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道CS50标头来自哪里,但我认为这是一门课程。
我可以看到两个问题:
int count_letters(字符串text);
in main:nery:
you redeclare函数而不是使用它并获取其返回值,请使用
int result = count_letters( text);
而不是。在这里:
您通过
text
是字符串(类型char*),但是%i(或%d)需要一个整数,您可以(并且应该)使用上一个函数的返回值在这种情况下:因此,printf(“%i \ n”,结果);
(如果您在1中建议进行修改)。否则在标准C中(请记住,我保持简单,并尝试做类似的代码的事情,因此缺少错误检查):
I don't know where the cs50 header comes from but I assume it's from a course.
I can see two problems:
int count_letters(string text);
in main:Here:
You redeclare the function instead of using it and getting it's return value, use something like
int result=count_letters(text);
instead.Here:
You pass
text
which is a string (type char*) but %i (or %d) requires an integer, you can (and should) use the return value of the previous function in this case : so something likeprintf("%i\n", result);
if you made the modification I suggested in 1).Otherwise in standard c (please keep in mind I kept it simple and tried to do something similar to your code so there are missing error checking):