【问题标题】:How to search for a name in a struct/file如何在结构/文件中搜索名称
【发布时间】:2015-12-02 23:28:46
【问题描述】:

我有一个包含两个名称的结构,但它们是字符形式 - 所以是一个数组 字符[2][10] 它应该是两个最多十个字符长的名称。 我想搜索它们。

    while (ans3==1)
{
    cout << "\nPlease enter the name you want to search"
        <<endl;
    cin >> searchName;
    for (int i=0; i < size; i++)
    {
        cout <<"\nsearching " <<endl;
        for (int k=0; k< 10; k++ )
        if ( MyData.name[i][k]==searchName[k])
        {
            cout << "\nName was found at position "<< k <<endl;
        }
        else 
            cout << "\nName not found at position " <<k <<endl;
    }

    cout << "\nDo you want to search for a name? (1 for y, 2 for n)" <<endl;
    cin >> ans3;
}

这编译,但不做我想让它做的事。有人可以帮忙吗。谢谢。

【问题讨论】:

  • for (int k=0; k&lt; 10; k++ ) 如果字符串少于 9 个字符,将在字符串末尾之后继续搜索。考虑改用strncmp

标签: c++ string file search struct


【解决方案1】:

您当前的结构假设名称从数组的索引 0 开始。 我建议将名称数组中的每个字符与搜索到的名称的第一个字符进行对比,直到您找到名称数组的末尾或找到匹配项。如果找到匹配项,则检查名称数组中剩余的字符与搜索字符串中的下一个字符。 因为现在您要检查的是两个字符串是否以相同的字母开头。 要返回名称的起始位置,请保留第一个匹配项的索引。 如果我的建议根本不是您想要的,您也可以使用 strcomp()。

【讨论】:

  • 谢谢。我写的那个,它有点初级,但它完成了工作。
  • 做了一个for循环,遍历两个名字,检查第一个字母,如果找到第一个字母,就会遍历整个单词。但只有一点——当它通过 b/c if 语句运行时,它会输出:found at 1, found at 2 found at....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 2019-01-06
  • 2021-12-02
  • 2015-09-07
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
相关资源
最近更新 更多