这个学期,我正在为一个课程编写一个程序,我需要让用户输入一个字符串,这个字符串应该是一个特定的.wav音频文件ts9_mono.wav的路径。
此音频文件的可能路径字符串如下所示:"C:/classes/ts9_mono.wav"
之后,我需要检查路径中指定的文件是否确实是.wav文件。对于赋值,我被告知,我需要查看路径字符串中的最后一个句点,并查看该句号之后的最后3-4个字符。
我认为最好的方法是使用strrchr(),例如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char path[200]; //this char array is for storing the path string
scanf("%s", &path); //let's pretend the user enters C:/classes/ts9_mono.wav
printf("%s", strrchr(path, '.'));
}现在屏幕的输出是:.wav
分配的这一部分我的计划是以某种方式存储由函数提供的.wav子字符串,并将其与另一个存储".wav"的char数组进行比较,以检查它们是否相同。
我知道,如果可以在字符串中找到字符的地址,strrchr将返回该字符的地址,但我不知道如何使用该指针执行我计划执行的上述操作。
发布于 2020-03-29 13:25:05
一种方法是将strchr的结果存储在char指针(char*)中,然后执行strcmp以查看输入是否是您想要的。示例:
char path[200];
char* result = NULL;
if (scanf("%199s", path)) != 1) // as per the comment from 'chqrlie for yellow blockquotes'
return 1;
result = strrchr(path, '.');
if (!result)
{
//There is no '.'
printf("There is no dot!");
}
else
{
if (strcmp(result, ".wav") == 0)
{
printf("The value ends with .wav!");
}
}https://stackoverflow.com/questions/60914195
复制相似问题