简体   繁体   English

如何在C ++中按字母顺序对标准输入字符串进行排序?

[英]How to sort standard input strings alphabetically in C++?

#include <iostream> 
using namespace std;

int main (int argc, char **argv)
{
    int i = 0, j = 0;
    string temp;

    for (i = 1; i < argc; ++i)
    {
         for (j = i+1; j < argc; ++j)
         {
              if (argv[i] > argv[j])
              {
                   temp = argv[i];
                   argv[i] = argv[j];
                   argv[j] = temp;
              }
          }
     }
}

I don't know why but i am getting this Error when i compile it. 我不知道为什么但是当我编译它时我得到这个错误。

trial2.cpp:109:14: error: assigning to 'char *' from incompatible type 'string' (aka'basic_string, allocator >') argv[j] = temp; trial2.cpp:109:14:错误:从不兼容的类型'string'(aka'basic_string,allocator>')中分配'char *'argv [j] = temp; ^ ~~~~ //temp is my temporary string. ^ ~~~~ // temp是我的临时字符串。

There are two errors in the code: 代码中有两个错误:

  1. As @hyde pointed out, temp should be char* and not string 正如@hyde指出的那样, temp应该是char*而不是string
  2. argv[i] > argv[j] looks like pointer comparison ie it will compare the value of the address rather than comparing the string. argv[i] > argv[j]看起来像指针比较,即它将比较地址的值而不是比较字符串。 I suggest using strcmp methods for comparing two char* (then you need to #include <string> to use this method) 我建议使用strcmp方法比较两个char* (然后你需要#include <string>来使用这个方法)

Suggested code (not sure if totally bug free or not, but hopefully it's the case): 建议的代码(不确定是否完全没有bug,但希望是这样的):

#include <iostream>
#include <string>
using namespace std;

int main (int argc, char **argv)
{
    int i = 0, j = 0;
    char* temp;

    for (i = 1; i < argc; ++i)
    {
         for (j = i+1; j < argc; ++j)
         {
              if (strcmp(argv[i] , argv[j]) > 0)
              {
                   temp = argv[i];
                   argv[i] = argv[j];
                   argv[j] = temp;
              }
          }
     }
    for(i = 0; i < argc; i++){
        cout << argv[i]<< endl;
    }
} 

Note the final for loop is to check if the output is sorted. 注意最后的for循环是检查输出是否已排序。 I tried your comparison argv[i] > argv[j] rather than strcmp and it does not seem to work on my machine. 我尝试了你的比较argv[i] > argv[j]而不是strcmp ,它似乎不适用于我的机器。

Error spring up becouse it fails cast type string to char * . 错误弹出因为它失败了将类型stringchar * But it must work reversed (therefore your temp = argv[i]; does't fails). 但它必须颠倒过来(因此你的temp = argv[i];不会失败)。 Don't write to argv (you can, but I do not recommend). 不要写argv (你可以,但我不建议)。 Simple way: Copy argv to to some array of string before sorting: ` 简单方法:在排序之前将argv复制到某个string数组:`

string *argv_strings = new string[argc - 1];
for(int i = 0; i < argc - 1; ++i)
{
    argv_strings[i] = new string(argv[i + 1]);
}

` `

and work with argv_strings instead argv Do not forget delete pointer after. 并使用argv_strings代替argv不要忘记delete指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM