数字と文字列Sのセットを入力として渡そうとしています。ここでは、文字列Sには名前の後にカンマが続き、その後に複数の数字の整数が続きます。プログラムは、対応する最高番号の名前を表示する必要があります。カンマ区切りの文字列で名前と整数値を読み取る方法は?
は、入力を考えてみましょう:出力のため
4
Will,13
Bob,7
Mary,56
Gail,45
:
Mary
メアリーに対応する数が最も高い56であるから。
私が直面しています問題は、ここでは2列に、すなわち
w[][] a[][]
を名前と電話番号を取得することです私は2次元配列を試してみましたが、私はカンマ区切りの値を読み取ることができないのです。だから、基本的に私は、文字配列にコンマと番号の配列にコンマの後の数字の前に名前を抽出したい
#include <stdio.h>
#include <ctype.h>
int main(){
char W[200][1000];//Two dimensional arrays to store names
int a[200];//To store the numbers
int i,n;
scanf("%d",&n);//Number of Strings
for (i=0; i<n; i++) {
scanf("%[^\n]s",W[i]);//To read the name
getchar();//To read the comma
scanf("%d",&a[i]);//To read the number
}
printf("\n");
for (i=0; i<n; i++) {
printf ("W[%d] = %s a[%d] = %d\n" ,i,W[i],i,a[i]);//Displaying the values
}
//To find out the maximum value
max = a[0];
for(i=0;i<n;i++){
if(a[i]>=max) { a[i] = max; pos = i; }
}
printf("\n%s",W[pos]); //Print the name corresponding to the name
return(0);
}
: これは私のコードです。
このコードを修正するにはどうすればよいですか?
はい私はscanfを使用できないという事実に同意します。確かに私はfgets()で試すことができます。ありがとう@Basile Starynkevitch –
私はmallocとscanf()の書式設定を使った解決策を持っています。あなたの提案には大変役に立つでしょう@Basile Starynkevitch –