问题描述
我正在尝试构建一个简单的程序来熟悉命令行功能,我似乎格式化错误,但我发现很难准确理解由此产生的错误消息的含义。我的意图是创建一个程序来检查命令行中的所有字符是否都是数字。这是我的代码:
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc,char *argv[])
{
for (int i = 0; i < strlen(argv); i++)
{
if (!isalnum(argv[i]))
{
printf("Please provide letters or numbers only");
}
else
{
printf("Success!");
}
}
}
我尝试编译时收到的错误消息是:c:9:32: error: incompatible pointer types passing 'char **' to parameter of type 'const char *'; dereference with * [-Werror,-Wincompatible-pointer-types]
。
解决方法
isalnum
是指向字符串的指针的数组(指针)。
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc,char *argv[])
{
for (int c = 1; c < argc; c++) // loop for checking each strings
{
for (int i = 0; i < strlen(argv[c]); i++) // loop for checking each characters in the strings
{
if (!isalnum(argv[c][i]))
{
printf("Please provide letters or numbers only");
}
else
{
printf("Success!");
}
}
}
}
正在检查一个字符,而不是整个字符串,因此您需要两个循环:检查每个字符串和检查字符串中的每个字符。
此代码不会收到警告:
size_t
但是您可能希望此代码具有改进功能:
- 只打印一次消息,而不是为每个字符打印一次。
- 使用
strlen()
循环直到字符串的长度。 - 在循环之前调用
puts
一次,而不是在每次迭代中调用。 - 使用
printf
而不是return 0;
在输出结束时打印换行符。 - 添加
#include
以说明代码返回 0。 - 删除不必要的
#include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc,char *argv[]) { int all_ok = 1; for (int c = 1; c < argc; c++) { size_t len = strlen(argv[c]); for (size_t i = 0; i < len; i++) { all_ok = all_ok && isalnum(argv[c][i]); } } if (!all_ok) { puts("Please provide letters or numbers only"); } else { puts("Success!"); } return 0; }
,包括非标准的。
#version 330 core
layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aTextureCoordinate;
out vec2 textureCoordinate;
uniform float textureOffsetX;
void main() {
gl_Position = vec4( aPosition.x,aPosition.y,1.0f,1.0f);
textureCoordinate = vec2(
textureOffsetX + aTextureCoordinate.x / 3.0f,aTextureCoordinate.y
);
}