Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何输入与给定数字一样多的单词数? #包括 #包括 int main() { 字数的整数,下限=1; 字符词; printf(“字数:”); scanf(“%d”&字数); for(lower_limit=1;lower_limit_C - Fatal编程技术网

如何输入与给定数字一样多的单词数? #包括 #包括 int main() { 字数的整数,下限=1; 字符词; printf(“字数:”); scanf(“%d”&字数); for(lower_limit=1;lower_limit

如何输入与给定数字一样多的单词数? #包括 #包括 int main() { 字数的整数,下限=1; 字符词; printf(“字数:”); scanf(“%d”&字数); for(lower_limit=1;lower_limit,c,C,scanf(“%str”,&word);原因,因为word指向字符,而不是字符数组。因此,任何情况都可能发生 旁注:“%str”应该是“%s” 下面是如何在C++中实现这一点: #include <stdio.h> #include <conio.h> int main() { int Number_of_words, lower_limit = 1; char word; printf ("Number of Words: "); s

scanf(“%str”,&word);
原因,因为
word
指向字符,而不是字符数组。因此,任何情况都可能发生

旁注:
“%str”
应该是
“%s”

下面是如何在C++中实现这一点:

#include <stdio.h>
#include <conio.h>

int main()
{
    int Number_of_words, lower_limit = 1;
    char word;

    printf ("Number of Words: ");
    scanf ("%d",&Number_of_words);

    for (lower_limit = 1; lower_limit <= Number_of_words; lower_limit += 1)
    {
        printf("Word: ");
        scanf("%str",&word);

    }
}
#包括
#包括
#包括
int main(){
标准::尺寸t sz;
std::cout>sz;
对于(std::string s;sz--&&std::cin>>s;/*nothing*/){

STD::P> >您在代码中使用了错误格式说明符> C++ >代码> STD::CUT和<代码> STD::CIN <代码> >格式>输出。其次,<代码> char < /C>保存一个字符而不是字符串。对于字符串,有代码> STD::String 。仅当您需要它们时才使用,并且通常为类型或常量保留大写起始字母

更正后的代码可能如下所示:

#include <cstddef>
#include <iostream>
#include <string>

int main() {
  std::size_t sz;
  std::cout << "Number: ";
  std::cin >> sz;

  for (std::string s; sz-- && std::cin >> s; /*nothing*/) {
    std::cout << s << '\n';
  }
}
#包括
#包括
int main(){
字数;
std::cout>字数;
对于(尺寸i=0;i字;
}
}

如果要实际存储所有单词以备将来使用,则应使用
std::vector
来存储它们。

应将它们存储在数组中,如果不想打印“Word:”不止一次,请将它移到“环”之外,只标记你正在使用的语言。你的代码是C++,而不是C。代码> %s//>需要一个字符数组,它足以存储所有输入字符加上一个终止的NUL。你已经给出了一个代码> char < /Cl>,这导致了未定义的行为…但是,唯一的C++是使用名称空间STD的 >;你可以安全地删除。这是C++还是C?试图读取C字符串到一个字符中不会很好。如果你想读比空字符串大的东西,你需要一个字符数组,比如:(@ Ayxan在C中用C++做什么有什么不同吗?很抱歉我是新的。我刚刚开始学习C大学(第一年)前几天,我以前学的语言是Python(这更容易)。谢谢。在C中做它和C++中有什么不同吗?@ toguulty C和C++真的是两种不同的语言。你所发布的代码看起来像C(除了<代码>使用命名空间STD;< /C>)修正错误后,C++也是有效的,但一般来说,C是有效的C++也是一个神话。问题是:我不知道C,所以我不能告诉你如何在C中完成它。
#include <string>
#include <iostream>

int main() {
    size_t number_of_words;   
    std::cout << "Number of Words: ";
    std::cin >> number_of_words;

    for (size_t i=0;i<number_of_words;++i) {
        std::string word;
        std::cout << "word: ";
        std::cin >> word;
    }
}