【问题标题】:not working scanf() when the product has 2 or more words当产品有 2 个或更多单词时,scanf() 不起作用
【发布时间】:2015-01-28 22:15:34
【问题描述】:

在超市自我发现的 200 种产品后面的代码。我想编写一个代码,首先显示所有可用产品,如果您键入其中一个,它会返回产品,即价格和数量。问题是,如果我键入scanf("%s",insertproduct);,它只能识别一个单词的产品。我在其他帖子中看到解决方案是写scanf("%[^\t\n]s",insertproduct);

但是当我这样做时,程序会忽略 scanf 并在

之后终止
printf("\nPlease select the desirable product to see it's quantity and price.\n\n");

一种想法是在多个单词的产品之间添加_,但这会花费很多时间。关于那个特定的 scanf() 有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <io.h>
#include <conio.h>
#include <fcntl.h>
#include <locale.h>

struct supermarket 
{
    char name[50];
    float price;
    int quantity;
};


int main(void) {
    struct supermarket product[200] = {
            {"sugar",1.2,127},
            {"greek coffee",2.03,200},
            {"milk",1.83,150},
            {"6pack small eggs",3.03,22},
            {"AAA bateries",2.2,20},
            {"AA bateries",2.3,29},
            {"6-pack big eggs",3.5,17},
            {"Frosties",4.5,30},
            {"All Bran",4.7,32},
            {"Special K",5.2,19},
            {"Honey Nut Loops",4.3,33},
            {"Coco Pops",4.09,28},
            {"White Bread",0.5,50},
            {"Black Bread",0.7,55},
            {"Toast Bread",1.73,66},
            {"cinamon",1.9,500},
            {"salt",1,423},
            {"pepper",1.29,325},
            {"coca cola 330ml",0.45,980},
            {"coca cola 500ml",0.9,745},
            {"coca cola 2lt",1.6,300},
            {"coca cola 1lt",1.3,1025},
            {"pepsi 330ml",0.45,980},
            {"pepsi 500ml",0.9,745},
            {"pepsi 2lt",1.6,300},
            {"pepsi 1lt",1.3,1025},
            {"7-up 330ml",0.6,682},
            {"fanta 330ml",0.4,741},
            {"fanta 1lt",1.1,120},
            {"fanta 500ml",0.75,267},
            {"mild mustard", 1.45,612},
            {"Hot mustard",1.85,387},
            {"Ketchup",1.6,400},
            {"mayonaise",2.1,346},
            {"apples",0.20,105},
            {"oranges",0.4,222},
            {"bananas",0.42,55},
            {"lettuce",0.12,141},
            {"potatoes 1kg",0.7,75},
            {"tomatoes",0.35,199},
            {"onions",0.11,425},
            {"grape-fruits",0.55,94},
            {"fresh salads",2.22,23},
            {"canned mushrooms",1.5,422},
            {"fresh mushrooms 200gr",1.98,55},
            {"oreos",1.59,257},
            {"Tide",2.47,730},
            {"Pampers",5.89,123},
            {"Mr Clean",5.01,35},
            {"Mr Proper",4.99,8},
            {"Kool-Aid",2.45,103},
            {"Knorr",3.05,308},
            {"Palmolive",3.01,617},
            {"Scotch-Brite",2.3,970},
            {"Cheetos",1.25,487},
            {"Top Ramen",6.27,109},
            {"Tomato sauce",0.59,1589},
            {"Goya Beans",3.21,300},
            {"Quaker Oats",3.39,32},
            {"Cream of Wheat",3.09,91},
            {"Nesquick",1.75,799},
            {"Silk Soy Milk",3.14,50},
            {"Philadelphia",4.15,6},
            {"Soy Sauce",1.09,45},
            {"A1 steak sauce",4.89,643},
            {"Barbeque sauce",5.79,94},
            {"Lays",2.5,567},
            {"Lays oregano",2.7,163},
            {"Pringles",1.85,421},
            {"Ajax",4.59,2548},
            {"Cleanex",5.27,941},
            {"Fountain",5.55,559},
            {"Mountain Dew",6.09,852},
            {"10 DVD",3.09,1896},
            {"Lipton ice tea",2.44,53},
            {"Lipton tea",1.29,633},
            {"Listerine",5.52,188},
            {"Centrum",9.99,588},
            {"Snapple",5.88,22},
            {"Purina 1",12.99,33},
            {"Wiskas",6.22,79},
            {"Pedigree Pal",9.99,10},
            {"Gatorade",2.13,1000},
            {"Amstel",0.99,111},
            {"Heineken",1.01,155},
            {"Guiness",1.8,77},
            {"McFarland",1.65,74},
            {"Estrella Damn",1.32,488},
            {"Stella Artois",0.87,14},
            {"Corona",1.11,347},
            {"Pilsner",1.74,166},
            {"Budweiser",1.77,654},
            {"Chimay Blue",2.12,344},
            {"Chimay Red",2.35,179},
            {"Chimay Black",2.55,333},
            {"Chimay Yellow",2.65,198},
            {"Beck's",1.72,188},
            {"Carlsberg",1.67,843},
            {"Paulaner",2.89,42},
            {"Erdinger",3.02,7},
            {"Colgate",1.75,644},
            {"butter",1.28,399},
            {"Peanut-Butter",2.74,211},
            {"PB&J",3.15,25},
            {"Barilla Linguini",2.58,941},
            {"Barilla spaghetti",1.56,357},
            {"Barilla tortellini",2.08,700},
            {"Barilla papardelle",3.58,9}, 
            {"Barilla lazagne",2.99,88},
            {"Advil",7.99,499},
            {"pears",0.26,2985},
            {"peaches",0.27,2456},
            {"Kiwi",0.36,2145},
            {"nectarines",0.38,2365},
            {"melon",0.39,951},
            {"watermellon",0.4,961},
            {"grapes",0.53,582},
            {"cherries",0.6,714},
            {"olives",0.09,936},
            {"pickles",0.87,195}, 
            {"halvah",1.33,2015},
            {"frulite orange-juice",1.61,478},
            {"frulite lemon-juice",1.62,477},
            {"frulite pineapple-juice",1.63,456},
            {"frulite carrot-juice",1.64,698},
            {"frulite banana-juice",1.65,874},
            {"frulite mixed-juice",1.66,599},
            {"rusks 160gr",1.35,588},
            {"rusks 320gr",2.03,589},
            {"rusks 400gr",2.72,523},
            {"rusks 500gr",3.74,542},
            {"vanila biscuits",3.30,699},
            {"cinamon biscuits",3.32,698},
            {"almond biscuits",3.35,612},
            {"butter biscuits",3.54,609},
            {"chocolate biscuits",3.41,59},
            {"cherry croissant",0.47,1025},
            {"apricot croissant",0.48,1058},
            {"chocolate croissant",0.41,1089},
            {"vanilla croissant",0.41,1054},
            {"vanilla-chocolate croissant",0.74,1036},
            {"cocoa croissant",0.27,1011},
            {"double-sized croissant",1.4,555},
            {"Derby",0.24,1000},
            {"Kinder Bueno",1.22,642},
            {"Kinder egg",0.91,377},
            {"Nivea hair-gel",5.88,417},
            {"Fructise hair-gel",5.97,429},
            {"Excellence hair-gel",4.88,437},
            {"mixed cake",3.99,11},
            {"chocolate cake",3.26,31},
            {"vanilla cake",3.36,44},
            {"orange cake",3.46,66},
            {"orange-chocolate cake",3.86,94},
            {"raisins cake",3.06,52},
            {"vakalaos",6.98,20},
            {"galeos",7.40,30},
            {"frozen shrimps",13.80,40},
            {"gavros",5.98,50},
            {"frozen octopus",6.36,90},
            {"fresh octopus",7.23,70},
            {"fresh shrimps",15.98,80},
            {"espresso",2.25,1896},
            {"6 chicken legs",6.66,11},
            {"2 chicken breasts",4.59,37},
            {"whole chicken",3.12,45},
            {"roasted chicken",4.97,48},
            {"capuccino",2.55,1478},
            {"jacobs vanilla",4.96,2458},
            {"jacobs chocolate",4.85,2365},
            {"jacobs caramel",4.87,2148},
            {"jacobs classic",4.59,1895},
            {"liquid fabric softener",5.22,1025},
            {"concentrated fabric softener",6.22,1048},
            {"noxzema saving foam 200ml",2.2,4832},
            {"loreal saving foam 200ml",2.6,613},
            {"nivea saving foam 200ml",2.8,2000},
            {"gillette saving foam 200ml",2.32,992},
            {"bic saving foam 200ml",2.13,469},
            {"noxzema saving foam 400ml",4.44,817},
            {"loreal saving foam 400ml",4.42,802},
            {"nivea saving foam 400ml",4.77,808},
            {"gillette saving foam 400ml",5.25,707},
            {"bic saving foam 400ml",5.21,303},
            {"Giotis baby-cream",7.10,111},
            {"Nounou baby-cream",7.05,223},
            {"Farin lacte baby-cream",6.82,334},
            {"Nutricia baby-cream",8.5,445},
            {"Ariel 5kg",22.5,556},
            {"Ariel 2kg",10.94,667},
            {"Ariel 1kg",5.31,778},
            {"Elvive shampoo",6.99,889},
            {"Wash and go shampoo",4.98,991},
            {"Proderm shampoo",7.22,882},
            {"Pantene shampoo",6.44,773},
            {"Fructis shampoo",7.13,664},
            {"Gliss shampoo",3.19,552},
            {"toilet paper 8 rolls",3.77,668},
            {"toilet paper 12 rolls",5.99,3},
            {"toilet paper 16 rolls",6.54,13}
    };

    int choise;

    printf("Please enter 1 and hit Enter to continue.\n");
    scanf("%d", &choise);

    int i;

    printf("See our full list of products.\n\n");
    for(i = 0 ; i < 200 ; i++){
        printf("%s\n", product[i].name);
    }
    char insertproduct[50];

    printf("\nPlease select the desirable product to see it's quantity and price.\n\n");
    scanf("%s", insertproduct);
    for (i = 0 ; i < 200 ; i++) {
        if(strcmp(product[i].name, insertproduct) == 0) {
            printf("You selected: %s. Price: %.2f euro. Quantity: %d items.\n\n", 
                product[i].name, 
                product[i].price, 
                product[i].quantity);
        }
    }
    return 0;
}

【问题讨论】:

  • 这些都是你手动输入的吗?
  • 试试scanf(" %[^\t\n]",insertproduct);
  • 您听说过数据库系统吗?
  • 我尝试了 BLUEPIXY 的建议尝试 scanf(" %[^\t\n]",insertproduct);它奏效了。奇怪的是,昨天我尝试输入 scanf("%[^\t\n]",insertproduct);它没有用。似乎 " 和 % 之间的空格完全不同。

标签: c scanf


【解决方案1】:

scanf() 会在找到空白字符时停止读取,尽管您可以修复代码并使scanf() 工作,我认为在这种情况下最好使用fgets()

clearStdin()函数,在下面的代码中有两个任务,先清除'\n'等可能留下的空格

scanf("%d", &choise);

如果您输入了无效数据,允许重复调用而不会导致无限循环,然后如果输入有效,则也接受它们,以便fgets() 在流中找不到'\n' 并返回带有一个空字符串。

试试这个更正的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct supermarket
{
    char name[50];
    float price;
    int quantity;
};

void clearStdin()
{
    int chr;
    while (((chr = getchar()) != EOF) && (chr != '\n'));
}


int main(void) {
    struct supermarket product[200] = {
            {"sugar",1.2,127},
            {"greek coffee",2.03,200},
            {"milk",1.83,150},
            {"6pack small eggs",3.03,22},
            {"AAA bateries",2.2,20},
            {"AA bateries",2.3,29},
            {"6-pack big eggs",3.5,17},
            {"Frosties",4.5,30},
            {"All Bran",4.7,32},
            {"Special K",5.2,19},
            {"Honey Nut Loops",4.3,33},
            {"Coco Pops",4.09,28},
            {"White Bread",0.5,50},
            {"Black Bread",0.7,55},
            {"Toast Bread",1.73,66},
            {"cinamon",1.9,500},
            {"salt",1,423},
            {"pepper",1.29,325},
            {"coca cola 330ml",0.45,980},
            {"coca cola 500ml",0.9,745},
            {"coca cola 2lt",1.6,300},
            {"coca cola 1lt",1.3,1025},
            {"pepsi 330ml",0.45,980},
            {"pepsi 500ml",0.9,745},
            {"pepsi 2lt",1.6,300},
            {"pepsi 1lt",1.3,1025},
            {"7-up 330ml",0.6,682},
            {"fanta 330ml",0.4,741},
            {"fanta 1lt",1.1,120},
            {"fanta 500ml",0.75,267},
            {"mild mustard", 1.45,612},
            {"Hot mustard",1.85,387},
            {"Ketchup",1.6,400},
            {"mayonaise",2.1,346},
            {"apples",0.20,105},
            {"oranges",0.4,222},
            {"bananas",0.42,55},
            {"lettuce",0.12,141},
            {"potatoes 1kg",0.7,75},
            {"tomatoes",0.35,199},
            {"onions",0.11,425},
            {"grape-fruits",0.55,94},
            {"fresh salads",2.22,23},
            {"canned mushrooms",1.5,422},
            {"fresh mushrooms 200gr",1.98,55},
            {"oreos",1.59,257},
            {"Tide",2.47,730},
            {"Pampers",5.89,123},
            {"Mr Clean",5.01,35},
            {"Mr Proper",4.99,8},
            {"Kool-Aid",2.45,103},
            {"Knorr",3.05,308},
            {"Palmolive",3.01,617},
            {"Scotch-Brite",2.3,970},
            {"Cheetos",1.25,487},
            {"Top Ramen",6.27,109},
            {"Tomato sauce",0.59,1589},
            {"Goya Beans",3.21,300},
            {"Quaker Oats",3.39,32},
            {"Cream of Wheat",3.09,91},
            {"Nesquick",1.75,799},
            {"Silk Soy Milk",3.14,50},
            {"Philadelphia",4.15,6},
            {"Soy Sauce",1.09,45},
            {"A1 steak sauce",4.89,643},
            {"Barbeque sauce",5.79,94},
            {"Lays",2.5,567},
            {"Lays oregano",2.7,163},
            {"Pringles",1.85,421},
            {"Ajax",4.59,2548},
            {"Cleanex",5.27,941},
            {"Fountain",5.55,559},
            {"Mountain Dew",6.09,852},
            {"10 DVD",3.09,1896},
            {"Lipton ice tea",2.44,53},
            {"Lipton tea",1.29,633},
            {"Listerine",5.52,188},
            {"Centrum",9.99,588},
            {"Snapple",5.88,22},
            {"Purina 1",12.99,33},
            {"Wiskas",6.22,79},
            {"Pedigree Pal",9.99,10},
            {"Gatorade",2.13,1000},
            {"Amstel",0.99,111},
            {"Heineken",1.01,155},
            {"Guiness",1.8,77},
            {"McFarland",1.65,74},
            {"Estrella Damn",1.32,488},
            {"Stella Artois",0.87,14},
            {"Corona",1.11,347},
            {"Pilsner",1.74,166},
            {"Budweiser",1.77,654},
            {"Chimay Blue",2.12,344},
            {"Chimay Red",2.35,179},
            {"Chimay Black",2.55,333},
            {"Chimay Yellow",2.65,198},
            {"Beck's",1.72,188},
            {"Carlsberg",1.67,843},
            {"Paulaner",2.89,42},
            {"Erdinger",3.02,7},
            {"Colgate",1.75,644},
            {"butter",1.28,399},
            {"Peanut-Butter",2.74,211},
            {"PB&J",3.15,25},
            {"Barilla Linguini",2.58,941},
            {"Barilla spaghetti",1.56,357},
            {"Barilla tortellini",2.08,700},
            {"Barilla papardelle",3.58,9},
            {"Barilla lazagne",2.99,88},
            {"Advil",7.99,499},
            {"pears",0.26,2985},
            {"peaches",0.27,2456},
            {"Kiwi",0.36,2145},
            {"nectarines",0.38,2365},
            {"melon",0.39,951},
            {"watermellon",0.4,961},
            {"grapes",0.53,582},
            {"cherries",0.6,714},
            {"olives",0.09,936},
            {"pickles",0.87,195},
            {"halvah",1.33,2015},
            {"frulite orange-juice",1.61,478},
            {"frulite lemon-juice",1.62,477},
            {"frulite pineapple-juice",1.63,456},
            {"frulite carrot-juice",1.64,698},
            {"frulite banana-juice",1.65,874},
            {"frulite mixed-juice",1.66,599},
            {"rusks 160gr",1.35,588},
            {"rusks 320gr",2.03,589},
            {"rusks 400gr",2.72,523},
            {"rusks 500gr",3.74,542},
            {"vanila biscuits",3.30,699},
            {"cinamon biscuits",3.32,698},
            {"almond biscuits",3.35,612},
            {"butter biscuits",3.54,609},
            {"chocolate biscuits",3.41,59},
            {"cherry croissant",0.47,1025},
            {"apricot croissant",0.48,1058},
            {"chocolate croissant",0.41,1089},
            {"vanilla croissant",0.41,1054},
            {"vanilla-chocolate croissant",0.74,1036},
            {"cocoa croissant",0.27,1011},
            {"double-sized croissant",1.4,555},
            {"Derby",0.24,1000},
            {"Kinder Bueno",1.22,642},
            {"Kinder egg",0.91,377},
            {"Nivea hair-gel",5.88,417},
            {"Fructise hair-gel",5.97,429},
            {"Excellence hair-gel",4.88,437},
            {"mixed cake",3.99,11},
            {"chocolate cake",3.26,31},
            {"vanilla cake",3.36,44},
            {"orange cake",3.46,66},
            {"orange-chocolate cake",3.86,94},
            {"raisins cake",3.06,52},
            {"vakalaos",6.98,20},
            {"galeos",7.40,30},
            {"frozen shrimps",13.80,40},
            {"gavros",5.98,50},
            {"frozen octopus",6.36,90},
            {"fresh octopus",7.23,70},
            {"fresh shrimps",15.98,80},
            {"espresso",2.25,1896},
            {"6 chicken legs",6.66,11},
            {"2 chicken breasts",4.59,37},
            {"whole chicken",3.12,45},
            {"roasted chicken",4.97,48},
            {"capuccino",2.55,1478},
            {"jacobs vanilla",4.96,2458},
            {"jacobs chocolate",4.85,2365},
            {"jacobs caramel",4.87,2148},
            {"jacobs classic",4.59,1895},
            {"liquid fabric softener",5.22,1025},
            {"concentrated fabric softener",6.22,1048},
            {"noxzema saving foam 200ml",2.2,4832},
            {"loreal saving foam 200ml",2.6,613},
            {"nivea saving foam 200ml",2.8,2000},
            {"gillette saving foam 200ml",2.32,992},
            {"bic saving foam 200ml",2.13,469},
            {"noxzema saving foam 400ml",4.44,817},
            {"loreal saving foam 400ml",4.42,802},
            {"nivea saving foam 400ml",4.77,808},
            {"gillette saving foam 400ml",5.25,707},
            {"bic saving foam 400ml",5.21,303},
            {"Giotis baby-cream",7.10,111},
            {"Nounou baby-cream",7.05,223},
            {"Farin lacte baby-cream",6.82,334},
            {"Nutricia baby-cream",8.5,445},
            {"Ariel 5kg",22.5,556},
            {"Ariel 2kg",10.94,667},
            {"Ariel 1kg",5.31,778},
            {"Elvive shampoo",6.99,889},
            {"Wash and go shampoo",4.98,991},
            {"Proderm shampoo",7.22,882},
            {"Pantene shampoo",6.44,773},
            {"Fructis shampoo",7.13,664},
            {"Gliss shampoo",3.19,552},
            {"toilet paper 8 rolls",3.77,668},
            {"toilet paper 12 rolls",5.99,3},
            {"toilet paper 16 rolls",6.54,13}
    };

    int  choise;
    int  i;
    char insertproduct[50];

    printf("Please enter 1 and hit Enter to continue.\n");
    while (scanf("%d", &choise) != 1)
    {
        printf("invalid, choice\n");
        printf("Please enter 1 and hit Enter to continue.\n");

        clearStdin();
    }
    clearStdin();

    printf("See our full list of products.\n\n");
    for (i = 0 ; i < 200 ; i++) {
        printf("%s\n", product[i].name);
    }

    printf("\nPlease select the desirable product to see it's quantity and price.\n\n");
    if (fgets(insertproduct, sizeof(insertproduct), stdin) != NULL)
    {
        size_t length;

        length = strlen(insertproduct);
        /* remove possible '\n' consumed by fgets */
        if (insertproduct[length - 1] == '\n')
            insertproduct[length - 1] = '\0';
        for (i = 0 ; i < 200 ; i++) {
            if (strcmp(product[i].name, insertproduct) == 0) {
                printf("You selected: %s.\n\tPrice: %.2f euro.\n\tQuantity: %d items.\n\n",
                    product[i].name,
                    product[i].price,
                    product[i].quantity);
            }
        }
    }
    return 0;
}

您应该知道的一件事是 fgets() 确实从流中读取了 '\n' 字符,因此在比较之前,您应该将其从保存输入字符串的数组中删除。

【讨论】:

  • 一些小想法:200行数据不用全部贴出来。 2) 建议在[length - 1] 之前检查length != 0 3) 由于长度要少1,为什么不insertproduct[--length] = '\0'? 4)次要:首先检查'\n',如while (((chr = getchar()) != '\n') &amp;&amp; (chr != EOF));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多