C++:解析一个没有stringstream的字符串

js81xvg6  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(93)
int main()
{
  std:: string menuChoice;
  int nArrayNumber = 0;
  int nAuthorArrayNumber = 0;
  int nElementArrayNumber = 0;
  pCurrentMediaItem = aMediaItemArray;
  
  displayMediaMenu();
  while (!finished)
    {
      std::cin.clear();
      interActive = isatty(fileno(stdin));
      std:: cout << std::endl << "Menu[" << nArrayNumber << "]:";
      getline (std::cin, menuChoice);
      charOption(menuChoice, 
                 pCurrentMediaItem, 
                 nArrayNumber,
                 finished,
                 nAuthorArrayNumber,
                 nElementArrayNumber);

字符串
C++:我如何解析一个字符串,并将整数赋给其他变量,将名称赋给一个单独的字符串变量。
举例来说,您可以:必须输入作者的出生年份、死亡年份和姓名,并且必须将该字符串发送到一个switch语句,该语句将解析该字符串并将单独的成员分配给其他变量。

lc8prwob

lc8prwob1#

根据你对解析字符串c 1888 1999 Author Name的评论,你可以考虑用第一个字符创建一个switch语句。例如:

Author cAuthor;
switch(clever_name[0]) {
    case 'c':
        Author = find_author(clever_name);
        break;
    default:
        // do something else
}

字符串
Author是一个有名字、出生年份和死亡年份的类,find_author是下面可怕的意大利面条代码。我沿着了STL的字符串构造函数,find_first_offind_first_not_offind_last_of返回字符串中的一个位置。

Author find_author(std::string s) {
    std::string nums("0123456789");
    std::string chars(
         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrxtuvwxyz"
                      );
    size_t pos = s.find_first_of(nums); // find the first number
    int birth = std::atoi(
        std::string(
            s, // string to copy from
            pos, // position of first integer
            // the next line finds out how many characters we need to copy
            std::string(s.begin() + pos, s.end()).find_first_not_of(nums)
        ).c_str()
        );

    // increment pos to the next character that is not a number
    pos += std::string(s.begin() + pos, s.end()).find_first_not_of(nums);

    // then increment again to the next character that is a number
    pos += std::string(s.begin() + pos, s.end()).find_first_of(nums);

    // do the same thing again to find the next date
    int death = std::atoi(
        std::string(
            s,
            pos,
            std::string(s.begin() + pos, s.end()).find_first_not_of(nums)
        ).c_str()
        );

    // increment pos to the position of the first alphabetic character
    pos += std::string(s.begin() + pos, s.end()).find_first_of(chars);

    // do the same thing we did to find the numbers to extract the name
    std::string name =
        std::string(
            s,
            pos,
            std::string(
                   s.begin() + pos, s.end()
                        ).find_last_not_of(nums) + 1
            );
    return(Author(name, birth, death));
}

相关问题