我写了一个程序,将一些单元格和行转换为excel数据。这是代码:
#include <cstdlib>
#include <iostream>
using namespace std;
char dgt[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int input = 10;
int output = 26;
int main() {
char name[64];
std::cin.getline(name, 64);
string text = name;
char* temp;
int spacja = text.find(' ');
long liczba = strtol(text.substr(spacja+1,text.size()).c_str(), &temp, input);
string out = "";
liczba--;
for (int i = 32; true; i--) {
out = dgt[liczba % output - (i==32?0:1)] + out;
liczba = liczba / output;
if (liczba <= 0)
break;
}
cout << out << text.substr(0,spacja);
return 0;
}
我得到了90/100,在一次测试中它返回了不好的价值。错误在哪里?我无法检查它。
答案 0 :(得分:2)
首先,没有理由将dgt
声明为C风格的字符数组:
std::string dgt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
其次,您应该使用std::getline
代替cin.getline
:
std::string line;
std::getline(cin, line);
第三,您应该使用std::stol
代替strtol
:
std::string s = "123";
long liczba = std::stol(s);
您现在遇到的问题是由于您已宣布
char* temp; // an uninitialized pointer
然后你尝试使用它
long liczba = strtol(text.substr(spacja+1,text.size()).c_str(), &temp, input);
// ^^^^^ This will result in a runtime error
使用std::stol
可以避免此问题。
要做#2和#3,您需要包含<string>
。
答案 1 :(得分:0)
我使用以下方法解决了这个问题:
#include <cstdlib>
#include <iostream>
using namespace std;
char dgt[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int input = 10;
int output = 26;
string convert(long liczba) {
string out = "";
liczba--;
for (int i = 32; true; i--) {
char add = dgt[liczba % output - (i==32?0:1)];
if(add==0) {
add='Z';
out = add + out;
liczba = liczba / output-1;
} else {
out = add + out;
liczba = liczba / output;
}
if (liczba <= 0)
break;
}
return out;
}
int main() {
char name[64];
std::cin.getline(name, 64);
string text = name;
char* temp;
int spacja = text.find(' ');
long liczba = strtol(text.substr(spacja+1,text.size()).c_str(), &temp, input);
cout << convert(liczba) << text.substr(0,spacja);
return 0;
}