c++ - 再次运行程序并将结果存储在数组中

标签 c++

<分区>

这是我的程序,用于匹配子字符串。我想更改程序中输入和输出的工作方式。

问题定义:

  • 提示用户输入多少个字符串(N)
  • N个字符串将分行输入
  • 对于每个字符串,
  • 如果它以“hackerrank”开头,则打印 1
  • 如果以“hackerrank”结尾则打印 2
  • 如果以“hackerrank”开头和结尾则打印 0
  • 如果以上都不是则打印-1

示例:

输入:

4
i love hackerrank
hackerrank is an awesome place for programmers
hackerrank
i think hackerrank is a great place to hangout



Output:
2
1
0
-1

这是我的实际代码。

int main()
{

    vector<string> token_store;
    string s,token;



    getline(cin,s);
    std::istringstream iss(s);


    while(iss>>token)
        token_store.push_back(token);   //splitting strings into tokens


    int len=token_store.size();        //storing size of vector

    if(token_store[0]=="hack" && token_store[len-1]=="hack")
       cout<<"first and last same";     //if first and last word of input string is hack
    else if(token_store[0]=="hack")
       cout<<"first matches";                                    //if first word of input string is hack
    else if(token_store[len-1]=="hack")
       cout<<"last matches";                                 //if last word of input string is hack

}

最佳答案

以下代码将读取输入并检查字符串“hackerrank”

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> token_store;
    int amount;
    string s;

    cin >> amount;
    cin.ignore();

    for(int i = 0; i < amount; i++){
        getline(cin, s);
    token_store.push_back(s);
    }

    string match = "hackerrank";

for(int i = 0; i < amount; i++){
    bool starts = false;
    bool ends = false;
    string str = token_store[i];

    if(str.length() < match.length()){
        std::cout << -1 << "\n";
        continue;
    }
    starts = str.substr(0, match.length()) == match; // Check if string starts with match
    ends = str.substr(str.length()-match.length()) == match; // Check if string ends with match

    if(starts && ends)
        std::cout << 0 << "\n";
    else if(starts)
        std::cout << 1 << "\n";
    else if(ends)
        std::cout << 2 << "\n";
    else
        std::cout << -1 << "\n";

    }
    return 0;
}

关于c++ - 再次运行程序并将结果存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19408115/

相关文章:

c++ - 为什么 std::shared_ptr 使用原子 cpu 操作

c++ - getline() 后的 For 循环不执行

c++ - #ifdef 指令末尾的额外标记

c++ - 如何通过 Rust FFI 调用 C++ 构造函数?

c++ - 保存计算器输入并在下一行重现它的问题

c++ - 给定指向节点的指针,删除该特定节点

c++ - Visual Studio 2015 (C++) : lock search word (ctrl+F) for all . cpp/.h

c++ - C++-运算符= self 分配检查

c++ - ASIC 设备的 OpenCL(或其他)编程?

c++ - 以下代码之间有什么区别,为什么一个有效而另一个无效?