为什么我的代码没有按预期工作?

时间:2014-12-24 18:17:19

标签: c++

我正在编写一个代码来输入几个字符串并比较字符串的长度,然后将较短的字符串打印到控制台输出。但是代码没有按预期工作,并且在给出任何输入集时,我得到的输出是一个空白屏幕(没有显示字符串)。谁能告诉我我做错了什么?

input数组包含用户提供的字符串,这些字符串也存在于a中,因此对于{中的特定值,行(string[i] == a[j])将执行为true {1}}。

a

我认为代码(#include <iostream> #include <string.h> using namespace std; int main() { long n, m; cin >> n >> m; char a[m][10], b[m][10]; // will print the shorter out of these two for (long i = 0; i < m; i++) cin >> a[i] >> b[i]; char input[n][10]; for (long i = 0; i < n; i++) cin >> input[i]; for (long i = 0; i < n; i++) { for (long j = 0; j < m; j++) { if (input[i] == a[j]) // checks which set of a,b does this input correspond to { if (strlen(a[j]) > strlen(b[j])) cout << b[j]; else cout << a[j]; if (i < n - 1) cout << " "; } } } } )有问题,但我不确定是什么。

1 个答案:

答案 0 :(得分:6)

问题在于这种比较:

input[i] == a[j]

它比较两个指针,而不是字符串。

更改为使用std::string或使用std::strcmp

相关问题