【发布时间】:2023-03-24 16:28:01
【问题描述】:
我有以下简单代码:
#include <cstdio>
#include <queue>
#include <iostream>
struct Pacient {
int ill_state;
int ev_num;
bool operator==(const Pacient& other) const {
return ill_state == other.ill_state && ev_num == other.ev_num;
}
bool operator<(const Pacient& other) const {
return (ill_state < other.ill_state) || (ill_state == other.ill_state && ev_num > other.ev_num); // má menšiu prioritu, ak čaká kratšie (vyššie číslo na kartičke pri vstupe do ambulancie
}
bool operator>(const Pacient& other) const {
return (ill_state > other.ill_state) || (ill_state == other.ill_state && ev_num < other.ev_num);
}
};
int main() {
char* ccmd;
std::priority_queue<Pacient> ps;
int ev_num, ill_state;
while (std::scanf("%s", ccmd)) {
std::string cmd(ccmd);
if (cmd == "dalsi") {
if (ps.empty()) {
std::printf("-1\n");
} else {
std::printf("%d\n", ps.top().ev_num);
ps.pop();
}
} else if (cmd == "pacient") {
std::scanf("%d%d\n", &ev_num, &ill_state);
Pacient new_ps;
new_ps.ev_num = ev_num;
new_ps.ill_state = ill_state;
ps.push(new_ps);
} else if (cmd == "koniec") {
break;
}
}
return 0;
}
编译并输入一些内容到标准输入后,我有以下段错误:
Program received signal SIGSEGV, Segmentation fault.
__strlen_sse2_pminub () at ../sysdeps/x86_64/multiarch/strlen-sse2-pminub.S:38
38 ../sysdeps/x86_64/multiarch/strlen-sse2-pminub.S: No such file or directory.
我使用的是 Ubuntu 13.10 64 位。 有人可以解释一下,是什么导致了这个问题?
注意:我使用的是 scanf 而不是 cin,因为我有使用 scanf、printf 而不是 cin、cout 的具体说明(来自学校)。否则我不会使用它。
【问题讨论】:
-
当您使用“%s”时,
scanf需要char *。也就是说,使用std::string和operator>>或std::getline。 -
@Aashish 是的,我可以,但我对此代码有使用 scanf 和 printf 的具体说明。
-
@chris 我已经在使用它了。
-
你的标题完全不符合标准:你不是使用
scanf读入std::string,你正试图读入char *,是一个 c 风格的字符串. -
@crashmstr 谢谢,已解决。
标签: c++