[英]How to search for specific strings and integers in a .txt file C and use them?
這段代碼是一個關於文件I / O的小型學習經驗,我還沒有完成:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
FILE *fP;
char so_name[64];
char user_name[64];
int number;
char continue_button;
time_t t;
system("TITLE Love-0-meter");
system("COLOR 4D");
srand((unsigned) time(&t));
number = (rand() %100);
printf("Hi and welcome to the love-o-meter, please fill in the details and see how much you and your SO"
" love each other!\n\nHave you used this program before?(Y/N)");
do
{
scanf(" %c", &continue_button);
}while(continue_button != 'n' && continue_button != 'N' && continue_button != 'Y' && continue_button != 'y');
system("CLS");
printf("Enter your SO's name: ");
scanf(" %s", so_name);
printf("Enter your name: ");
scanf(" %s", user_name);
printf("\n%s and %s, you love each other %d%%", so_name, user_name, number);
if(continue_button == 'N' || continue_button == 'n')
{
fP = fopen("Love-o-meter.txt", "w");
}
else
{
fP = fopen("Love-o-meter.txt", "a");
}
fprintf(fP, "%s %s %i\n", so_name, user_name, number);
fclose(fP);
return 0;
}
基本上用戶必須輸入2個名稱並將其與隨機數一起保存在.txt文件中。 但是在名稱保存之前,程序必須檢查它們之前是否以相同的順序使用過,並且已經在文件中。 如果之前確實使用過它們,程序不能生成新的數字,而是使用與2個名稱一起保存的數字並將其打印出來。
我一直在閱讀,但我無法弄清楚如何以及如何實現該程序能夠讀取以前保存的名稱和數字,並在找到匹配時使用它們。
您可以將您的位置保存在文件中,從頭開始掃描,然后返回到保存位置。
char name1[256], name2[256];
int val;
size_t pos = ftell(fP);
rewind(fP);
while(fscanf(fp, "%s %s %d", name1, name2, &val) == 3) {
// compare everything you need
}
fseek(fP, pos, SEEK_SET)
我希望我理解你的權利:)
你想要做的是解析文件。 為了在文本文件中使用字符串執行此操作,您需要一些方法來了解在何處查找為名稱存儲的名稱和結果。
正如前面提到的答案,使用職位是你應該真正研究的問題。 除此之外,您可能希望使用空格或字符分隔名稱和結果,並使用換行符分隔每個新條目。 您可以使用此功能,結合保存的位置,告訴您輸入的內容,以及您是否正在閱讀姓名或結果。
另外,你可能應該做對“的fopen”文檔一些閱讀,如本
我希望這就是你所尋求的。
我一直在閱讀,但我無法弄清楚如何以及如何實現該程序能夠讀取以前保存的名稱和數字,並在找到匹配時使用它們。
您已經正確描述了需要完成的工作。 為了做到這一點,你必須這樣做
a+
而不是a
) fscanf()
strcmp()
將它們與輸入的名稱進行比較 - 所以改變
printf("\n%s and %s, you love each other %d%%", so_name, user_name, number);
if(continue_button == 'N' || continue_button == 'n')
{
fP = fopen("Love-o-meter.txt", "w");
}
else
{
fP = fopen("Love-o-meter.txt", "a");
}
fprintf(fP, "%s %s %i\n", so_name, user_name, number);
至
if(continue_button == 'N' || continue_button == 'n')
{
fP = fopen("Love-o-meter.txt", "w");
}
else
{
char so_used[64];
char user_used[64];
int nuused;
fP = fopen("Love-o-meter.txt", "a+"); // append + read
while (fscanf(fP, "%s %s %i\n", so_used, user_used, &nuused) == 3)
if (!strcmp(so_used, so_name) && !strcmp(user_used, user_name))
{
number = nuused;
goto out;
}
}
fprintf(fP, "%s %s %i\n", so_name, user_name, number);
out:
printf("%s and %s, you love each other %d%%\n", so_name, user_name, number);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.