新人来了。我正在尝试使用 Mac OS X 学习 C++,并且在让调试器在 Eclipse 或 Netbeans 中工作时遇到严重问题(由于某些疯狂的原因无法获得 gdb)所以我决定尝试使用 Xcode。我编写了一个简单的排序程序,但不知道如何获取要填充的输出文件。这是我到目前为止所做的:
- 创建了一个姓名列表并将其作为 Names.txt 保存在 Sort 文件夹中。
- 进入 Xcode 中的“编辑方案”选项卡并添加两个参数 Names.txt 和 Output.txt。
- 运行程序没有错误或问题,但未创建 Output.txt。
- 在 Xcode 中,我通过“添加要排序的文件”将 Names.txt 拉入,还创建了一个空白的 Output.txt 文件并将其保存在 Sort 文件夹中。然后我也将 Output.txt 拉入 Xcode。
- 运行该程序,但仍然有一个空白的 Output.txt 文件。
这里是写的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Constants
#define BUFFER_SIZE 50
#define ARRAY_SIZE 20
// Global variables
int numElements = 0;
//function prototypes
void sort(string elements[]); // sort an array of strings in ascending order
void swap(string& s1, string& s2); // swap s1 and s2
int main(int argc, char *argv[])
{
char buffer[BUFFER_SIZE];
string listOfNames[ARRAY_SIZE];
string inputFileName;
string outputFileName;
ifstream inputFile;
ofstream outputFile;
if(argc != 3) {
cout << "Error: Please enter input and output files ";
cout << "as command line arguments !" << endl;
}
else {
inputFileName = argv[1];
outputFileName = argv[2];
inputFile.open(inputFileName.c_str());
outputFile.open(outputFileName.c_str());
// Read names from input file and store into array
while(!inputFile.eof() && numElements < (ARRAY_SIZE - 1)) {
inputFile.getline(buffer, BUFFER_SIZE);
string p = string(buffer);
listOfNames[numElements] = p;
numElements++;
}
// Sort elements in array
sort(listOfNames);
// Print elements in array to output file
for(int i = 0; i < numElements; i++) {
outputFile << listOfNames[i] << endl;
}
inputFile.close();
outputFile.close();
}
cout << "Sorting done!!!" << endl;
return 0;
}// end main
// perform bubble sort
// sort names in ascending order
void sort(string elements[]) {
bool change = true;
while(change) {
change = false;
for (int i = 0; i < (numElements - 1); i++) {
if (elements[i] > elements[i + 1]) {
swap(elements[i], elements[i+1]);
change = true;
}
}
}
}
// swapping 2 string
void swap(string& s1, string& s2) {
string temp = s1;
s1 = s2;
s2 = temp;
}
我确信代码是正确的,因为它在 Eclipse 中运行...我只是不知道如何让 Xcode 生成输出文件。
最佳答案
问题几乎可以肯定是您没有查看程序的工作目录。这就是创建“Output.txt”的地方,默认情况下,IIRC 位于 Xcode 为您的 ~/Library 文件夹内的 Xcode 应用程序支持区域中的项目创建的目录中。
我相信您可以在方案中设置工作目录。您还可以使用管理器打开 Xcode 为项目创建的文件夹。
请注意,这会同时影响您的 Output.txt 和 Names.txt; std::ifstream
不会仅仅因为您已将文件添加到 Xcode 项目而打开该文件。您要么需要使用绝对路径,要么将文件放在工作目录中。
It should build in the same folder as Sort.cpp
没有。它将在您的程序运行的“当前工作目录”中创建。不同的 IDE 会将其设置为不同的位置。如果您从 Terminal.app 运行您的程序,那么它将是您运行该程序时所在的任何位置。
I can't find any Output.txt on my computer
由于默认位置在 ~/Library 目录中的某处,如果您选中“搜索系统文件夹”选项或任何名称,Finder 中的搜索只会找到该文件。最好在您的方案或 Xcode 的管理器中查找 Xcode 将当前工作目录设置为什么。
关于c++ - 如何在 Xcode 中使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327159/