Skip to content

Instantly share code, notes, and snippets.

@l3ngli
Created October 2, 2025 17:31
Show Gist options
  • Select an option

  • Save l3ngli/4327a6482f50c868362c5fdecfd82529 to your computer and use it in GitHub Desktop.

Select an option

Save l3ngli/4327a6482f50c868362c5fdecfd82529 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
setlocale(0, "");
ofstream outFile("cities.txt");
if (!outFile) {
cout << "error\n";
return 1;
}
string cities[10] = {
"Beijing", "Shanghai", "Guangzhou", "Shenzhen", "Chengdu",
"Xi'an", "Hangzhou", "Wuhan", "Nanjing", "Suzhou"
};
for (int i = 0; i < 10; ++i) {
outFile << cities[i] << "\n";
}
outFile.close();
ifstream inFile("cities.txt");
if (!inFile) {
cout << "error\n";
return 1;
}
srand(time(0));
int randomCity = rand() % 10;
string line;
for (int i = 0; i <= randomCity; ++i) {
getline(inFile, line);
}
cout << "random city: " << line << "\n";
inFile.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment