Skip to content

Instantly share code, notes, and snippets.

@watermouth
Last active July 9, 2018 04:00
Show Gist options
  • Select an option

  • Save watermouth/261969b910151ce5600c6ff28479d25d to your computer and use it in GitHub Desktop.

Select an option

Save watermouth/261969b910151ce5600c6ff28479d25d to your computer and use it in GitHub Desktop.
char配列からstring文字列の生成に失敗した例(\0の付け忘れ)

https://beta.atcoder.jp/contests/soundhound2018-summer-qual のB問題 https://beta.atcoder.jp/contests/soundhound2018-summer-qual/tasks/soundhound2018_summer_qual_b の誤答例.

次のコードのようにstringに変換してから標準出力するとWAとなった。

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

int main() {
	string S;
	int w;
	cin >> S >> w;
	vector<char> res;
	for (int i=0; i<S.size(); ++i) {
		if ((i % w) == 0) res.push_back(S[i]); 
	}
	string s_res(res.data());
	cout << s_res << endl;
	return 0;
}

https://beta.atcoder.jp/contests/soundhound2018-summer-qual/submissions/2816691

原因は、stringのコンストラクタに入れる文字配列が終端文字\0を持っていないことで、次のように\0を追加しておけばACとなった。

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

int main() {
	string S;
	int w;
	cin >> S >> w;
	vector<char> res;
	for (int i=0; i<S.size(); ++i) {
		if ((i % w) == 0) res.push_back(S[i]); 
	}
	res.push_back('\0');
	string s_res(res.data());
	cout << s_res << endl;
	return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment