我知道一点C,现在我正在看看C++.我习惯使用char数组来处理C字符串,但是当我看到C++代码时,我看到有使用字符串类型和字符串数组的示例:
#include <iostream>
#include <string>
using namespace std;
int main () {
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
和
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your …Run Code Online (Sandbox Code Playgroud) 我想读取文件中的一行并在一行的n位置插入新行("\n")字符,以便将一个9个字符的行转换为三个3个字符的行,如这个:
"123456789" (before)
"123\n456\n789" (after)
Run Code Online (Sandbox Code Playgroud)
我试过这个:
f = open(file, "r+")
f.write("123456789")
f.seek(3, 0)
f.write("\n")
f.seek(0)
f.read()
Run Code Online (Sandbox Code Playgroud)
- >'123 \n56789'
我希望它不要替换位置n中的字符,而只是在该位置插入另一个("\n")字符.
有关如何做到这一点的任何想法?谢谢