簡體   English   中英

來自外部txt文件的c ++排行榜輸出不起作用

[英]c++ Leaderboard output from external txt file not working

您好,我一直在嘗試編寫一個程序,使編譯器從txt文件中獲取分數並將其以升序輸出,但是對於什么地方出錯,它沒有任何作用? 以及如何將其轉換為數組?

這是我正在使用的infile.txt:

1 John Doe     23567
2 Larry Bird       21889
3 Michael Jordan   21889
4 James Bond       13890
5 Gary Smith       10987
6 GJ               9889
7 Vivien vien      8990
8 Samantha Carl    6778
9 Gary  Lewes      5667
10 Sybil Saban     4677

該程序:

#include <iostream>
#include <fstream>
#include <string>
using std::ifstream;
using namespace std;


int main ()
{
    ifstream file_("infile.txt");
    int highscore;
    std::string name;
    int id;
    if (file_.is_open())
    {
    while(file_>>id >> name >> highscore)
    {

        std::cout<<id << " " <<name << " " <<highscore<<"";
    }
    file_.close();

    }


system ("pause");
return 0;

}

使用時

file_>> id >> name >> highscore

只讀取名字,不讀取任何內容到highscore ,流進入錯誤狀態,並且循環立即中斷。

您需要使用:

std::string firstName;
std::string lastNmae;

file_ >> id >> firstName >> lastName >> highscore

更新資料

存在

6 GJ               9889

該文件中的文件使簡單讀取文件變得困難。 您必須使用完全不同的策略。

  1. 逐行讀取文件。
  2. 標記每行。
  3. 從第一個令牌中提取ID。
  4. 從最后一個令牌中提取高分。
  5. 組合中間標記以形成名稱。

這就是我的想法:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using std::ifstream;
using namespace std;

int main ()
{
   ifstream file_("infile.txt");

   int highscore;
   std::string name;
   int id;
   if (file_.is_open())
   {
      std::string line;
      while ( getline(file_, line) )
      {
         std::string token;
         std::istringstream str(line);
         std::vector<std::string> tokens;
         while ( str >> token )
         {
            tokens.push_back(token);
         }

         size_t numTokens = tokens.size();
         if ( numTokens < 2 )
         {
            // Problem
         }
         else
         {
            id = std::stoi(tokens[0]);
            highscore = std::stoi(tokens.back());

            name = tokens[1];
            for ( size_t i = 2; i < numTokens-1; ++i )
            {
               name += " ";
               name += tokens[i];
            }

            std::cout << id << " " << name << " " << highscore << std::endl;
         }
      }
   }
}

將所有這些數據點收集在一個結構中,然后將您的輸入解析為這些結構的數組。

解析輸入時,您需要注意:1)>>實際如何工作2)指定的輸入文件具有1和2個單詞的名稱3)字符串可以使用+ =運算符,這可能很方便。

完成此操作后,您將需要按其得分成員對該結構數組進行排序,然后按順序輸出該數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM