我正在尝试检索用户输入,并找出他们是否在输入结尾添加了“.txt”。如果他们有,什么都不做,如果没有 - 做点什么。
以下是我到目前为止的一些代码:(argv [3]和[4]是用户的输入):
int main(int argc, char *argv[])
{
if (strlen(argv[3]) > 4){
usernames = strcpy(argv[2], ".txt");
}
if (strlen(argv[4]) > 4){
passwords = strcpy(argv[3], ".txt");
}
}
我已经在Python中掌握了它,我只是无法将其转换为C编程。这是我的Python版本:
#Ask user for a file name
while True:
inp = raw_input("Enter file name: ")
if len(inp) > 0:
break
else:
print "No file name givin, please try again"
#Check if file name has ".txt" on the end
if inp[-4:] != ".txt":
inp = str(inp)+".txt"
答案 0 :(得分:2)
C和python是非常不同的语言 - 最大的区别之一是需要静态声明变量。在您的代码中,必须声明变量usernames
和passwords
以及允许赋值的正确类型。这里有一些代码可以添加" .txt"根据代码中的条件使用用户名或密码。
#include "stdio.h" /* Allows us to call printf */
#include "string.h" /* Allows us to use string functions (strlen, strcmp, ctrcpy) */
int main(int argc, char *argv[])
{
size_t SIZE = 100;
char usernames[SIZE], passwords[SIZE]; /* Create char arrays to store our inputs */
printf("O usernames: %s, O passwords %s\n", argv[2], argv[3]); /* Print input */
if (strlen(argv[3]) > 4) {
strcpy(usernames, argv[2]); /* Copy argv[2] to usernames */
if (strcmp(usernames + strlen(usernames) - 4, ".txt") )
strcat(usernames, ".txt");
}
if (strlen(argv[4]) > 4) {
strcpy(passwords, argv[3]); /* Copy argv[3] to passwords */
if (strcmp(passwords + strlen(passwords) - 4, ".txt") )
strcat(passwords, ".txt");
}
printf("U usernames: %s, U passwords %s\n", usernames, passwords); /* Print output */
return 0;
}
我们使用strcpy
将char数组从argv
复制到usernames
。我们还使用strcmp
来检查后4个字符是否为.txt
。我的代码中的strcmp
使用一些指针数学来确保我们检查最后4个字符。我们也对passwords
进行相同的检查。
./a.out 1 uname upass foobar
O usernames: uname, O passwords upass.txt
U usernames: uname.txt, U passwords upass.txt
答案 1 :(得分:1)
您可以使用:
#include <stdio.h>
#include <string.h>
int main(void) {
int SIZE = 100;
char string[SIZE];
scanf("%s", string);
if(!strcmp(&(string[strlen(string)-4]), ".txt"))
//do something
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
int SIZE = 100;
char string[SIZE];
scanf("%s", string);
if(strcmp(&(string[strlen(string)-4]), ".txt"))
strcat(string, ".txt");
printf("%s\n", string); //all strings ends with ".txt" now
return 0;
}