C ++:如何将数组的内容与用户输入进行比较?

时间:2016-09-08 19:42:54

标签: c++ arrays compare

我是编程新手,所以对于大多数人来说,我的下一个问题看起来很容易回答。我们走了:

  1. 我有一组带有预定义内容的字符串。
  2. 我要求用户提供一些意见。
  3. 我想看看输入是否与数组中的一个元素相同。 3A。如果匹配,我想打印出阵列的“块”。 3B。如果没有匹配,我想通知用户没有匹配。
  4. 到目前为止,我设法直到第3a点,但没有进一步。请问你能给我一个建议吗? 这是我的代码(let)到目前为止:

    string fixed_array[4] = {"apple", "orange", "banana", "kiwi"};
    cout << "Please enter something:\n";
    string user_input;
    cin >> user_input;
    for (int i=0; i!=4; i++) {
        if (user_input == fixed_array[i]) {cout << "Fruit is in " << i << "\n";}
    

    不幸的是我不知道如何通知用户所请求的水果是否不在数组中,好像我在'if'之后添加'else',程序自然会每次都写出'not found'消息与数组元素不匹配。

    我在考虑循环的退出信号(bool可能?):如果循环内有匹配:true,如果没有匹配:false。然后在一个简单的'if'语句中使用这个bool打印出'not found'消息。

    有可能这样做,还是我完全偏离了?

    提前致谢!

4 个答案:

答案 0 :(得分:0)

如果找到的元素如下所示,您可以使用found设置为true的标记:

bool found = false;
string fixed_array[4] = {"apple", "orange", "banana", "kiwi"};
cout << "Please enter something:\n";
string user_input;
cin >> user_input;
for (int i=0; i!=4; i++) {
    if (user_input == fixed_array[i]) {
        cout << "Fruit is at index " << i << "\n";
        found = true; 
        break; //So the loop ends at the current index. This is not needed though
    }
}
if (!found)
{
    std::cout << "Not Found!\n";
}

答案 1 :(得分:0)

使用

  

std::find

搜索数组。

然后使用

  

std::distance

获取索引。

以下是示例代码

#include <string>
#include <iterator>
#include <iostream>

int main()
{
    std::string fixed_array[4] = { "apple", "orange", "banana", "kiwi" };

    std::cout << "Please enter something: ";
    std::string user_input;
    std::cin >> user_input;

    auto start = std::begin(fixed_array);
    auto end = std::end(fixed_array);

    auto foundLocation = std::find(start, end, user_input);

    bool isFound = foundLocation != end;

    if (isFound) {
        int index = std::distance(fixed_array, foundLocation);
        std::cout << "Found " << user_input << " at index " << index << std::endl;
    }
    else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

答案 2 :(得分:0)

你可以简单地在你的for循环中添加一个else if语句来检查输入是否不仅仅与输出不同,但是如果它是你的水果数组的最后一个元素:

string fixed_array[4] = {"apple", "orange", "banana", "kiwi"};
cout << "Please enter something:\n";
string user_input;
cin >> user_input;
for (int i=0; i != 4; i++) {
    if (user_input == fixed_array[i]) {
        cout << "Fruit is in " << i << "\n";
        break;
    }
    else if (i == 3) {
        cout << "The fruit is not found.\n";
    }
}

这是有效的,因为如果找到了水果,else if语句将永远不会运行,如果找到了水果,但它不是for循环的最后一次运行,则else if将不会执行。只有在找不到水果并且for循环最后一次运行时它才会运行,因为这意味着水果不在数组中。

答案 3 :(得分:0)

我已对所需部分提出解释性意见。

    Path pp = FileSystems.getDefault().getPath("logs", "access.log");
    final int BUFFER_SIZE = 1024*1024; //this is actually bytes

    FileInputStream fis = new FileInputStream(pp.toFile());
    byte[] buffer = new byte[BUFFER_SIZE]; 
    int read = 0;
    while( ( read = fis.read( buffer ) ) > 0 ){
        // call your other methodes here...
    }

    fis.close();
相关问题