【问题标题】:Printing out strings stored in a vector打印出存储在向量中的字符串
【发布时间】:2016-04-04 14:18:19
【问题描述】:

这是一个基本问题,但我是 C++ 新手,所以提前道歉 :)

我似乎无法打印出存储在向量中的字符串。我使用了 std:: cout 和 printf 但 printf 似乎给出了错误“程序已停止工作”。我哪里错了?

这是带有 std::cout 的代码:-

   #include <iostream> 
   #include <cstdio>         
   #include <vector> 
   #include <fstream> 
   using namespace std;

    int main(){ 
     int np; 
     string temp;  

     scanf("%d", &np); 
     vector <int> money;
     vector <string> names;  

        for(int i = 0; i< np; i++){
          scanf("%s", &temp); 
          names.push_back(temp); 
          cout << names[i] << endl; 
       } 

   return 0;
   }

这根本没有返回任何字符串。

我用 printf 试过的另一个程序是完全一样的,只是 cout 行被替换为:

printf("%s", &names[i]); 

【问题讨论】:

  • 使用 cin
  • 我认为你需要一本好的初学者书籍,here's a list of a few
  • 如果scanf("%s", &amp;temp);没有当着你的面抛出编译器警告,你需要将你的警告级别提高到更迂腐的程度。

标签: c++ string vector stl printf


【解决方案1】:

您不应该使用scanf 来读取std::string,因为%s 修改后接受char*。您也不应该使用printf("%s", &amp;names[i]); 来打印std::string 对象。

scanfprintf 是 C 函数。 C 语言中没有std::string 类型,因此它们使用的是普通字符数组。

您应该使用std::cinstd::cout,而不是scanfprintf

std::string str;
std::cin >> str; // input str
std::cout << str; // output str

【讨论】:

    【解决方案2】:

    您不能立即使用scanf() 读取整数。

    这应该可行:

    int np;
    std::string temp;
    
    std::cout << "Enter the size: ";
    std::cin >> np;
    //vector <int> money;
    std::vector<std::string> names;
    
    for (int i = 0; i< np; i++) {
        std::cin >> temp;
        names.push_back(temp);
        std::cout << names[i] << endl;
    }
    

    【讨论】:

    • 嗯,用scanf 读取整数并没有错(尽管这不是C++ 方式)。
    【解决方案3】:

    您需要对代码进行两点更改。 首先,,scanf() 不支持任何 c++ 类。您可以在link 上阅读更多相关信息。 第二,要替换scanf(),可以使用getline(cin, temp)。为了使用它,您应该在调用 getline 之前添加一行 cin.ignore(); 因为您输入一个数字并按 Enter 一个 '\n' 字符会插入到 cin下次调用 getline 时将使用的缓冲区。

       #include <iostream> 
       #include <cstdio>         
       #include <vector> 
       #include <fstream> 
       using namespace std;
    
        int main(){ 
         int np; 
         string temp;  
    
         scanf("%d", &np); 
         vector <int> money;
         vector <string> names;  
         cin.ignore();
            for(int i = 0; i< np; i++){
              getline(cin, temp);
              names.push_back(temp); 
              cout << names[i] << endl; 
           } 
    
       return 0;
       }
    

    查看代码here的工作演示。

    我希望我能够正确解释它。

    【讨论】:

    • 非常感谢。 :) 你认为 getline 比仅仅使用 std::cin 更有效吗?
    • 你可以根据需要使用其中任何一个。 cin,忽略空格、制表符和换行符。在大多数情况下,您希望用户输入的不可见字符也存储在字符串中。在这种情况下,您使用 getline。有关详细信息,请参阅此链接:programmingincpp.com/standard-input-function.html
    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2016-09-18
    • 2012-08-14
    相关资源
    最近更新 更多